Last active
July 7, 2018 00:00
-
-
Save asethia/b8ebc642001a9f26e7c0fc74c6ecfec1 to your computer and use it in GitHub Desktop.
Write a method to replace all spaces in a string with '%20'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Write a method to replace all spaces in a string with '%20: | |
* You may assume that the string has sufficient space at the end to hold the additional characters | |
* Input: "hello world " | |
* Output: "hello%20world" | |
* Created by Arun Sethia on 7/5/18. | |
*/ | |
trait URLify { | |
/** | |
* total time complexity O(3n) ~= O(n) | |
* | |
* @param input | |
* @return | |
*/ | |
def buildURLify(input: String): String = { | |
val data = removeTrailSpace(input) | |
//O(n) | |
data.foldLeft(new StringBuilder) { | |
case (builder, ' ') => builder.append("%20") | |
case (builder, x) => builder.append(x) | |
}.toString() | |
} | |
/** | |
* remove trail space O(n+n)=O(2n) | |
* | |
* @param in | |
* @return | |
*/ | |
private def removeTrailSpace(in: String): List[Char] = { | |
@tailrec | |
def space(in: List[Char]): List[Char] = { | |
//worst case O(n) | |
in match { | |
case h :: t if (h == ' ') => space(t) | |
case h :: t if (h != ' ') => in | |
} | |
} | |
//O(n) | |
space(in.reverse.toList).reverse | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment