Created
June 19, 2014 22:59
-
-
Save nealhu/e89e058b182a3fe24d88 to your computer and use it in GitHub Desktop.
CC_1_4
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
// Craking the Coding Interview | |
// 1.4 Write a method to replace all spaces in a string with'%20'. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the "true" length of the string. (Note: if implementing in Java, please use a character array so that you can perform this operation in place.) | |
// EXAMPLE | |
// Input: "Mr John Smith " | |
// Output: "Mr%20Dohn%20Smith" | |
import java.util.Arrays; | |
class SpaceReplacement { | |
public static char[] replaceSpace(char[] arr, int len) { | |
if (arr == null || len <= 0) return arr; | |
// calculate space number | |
int spaceNum = 0; | |
for (int i = 0; i < len; i++) { | |
if (arr[i] == ' ') { | |
spaceNum++; | |
} | |
} | |
if (spaceNum == 0) return arr; | |
// calculate new length | |
int newLen = spaceNum*2 + len; | |
// move chars back | |
int p1 = len-1; | |
int p2 = newLen-1; | |
while(p2 >= 0) { | |
if (arr[p1] == ' ') { | |
arr[p2--] = '0'; | |
arr[p2--] = '2'; | |
arr[p2--] = '%'; | |
} else { | |
arr[p2--] = arr[p1]; | |
} | |
p1--; | |
} | |
return arr; | |
} | |
private static char[] strToArr(String s) { | |
if (s == null) return null; | |
char[] arr = new char[s.replaceAll(" ", "%20").length()]; | |
for(int i = 0; i < s.length(); i++) { | |
arr[i] = s.charAt(i); | |
} | |
return arr; | |
} | |
public static void main(String[] args) { | |
assert Arrays.equals(replaceSpace(strToArr(""), 0), "".toCharArray()); | |
assert Arrays.equals(replaceSpace(strToArr(" "), 1), "%20".toCharArray()); | |
assert Arrays.equals(replaceSpace(null, 2), null); | |
assert Arrays.equals(replaceSpace(strToArr(" "), 2), "%20%20".toCharArray()); | |
assert Arrays.equals(replaceSpace(strToArr(" %20"), 4), "%20%20".toCharArray()); | |
assert Arrays.equals(replaceSpace(strToArr("%20 "), 4), "%20%20".toCharArray()); | |
assert Arrays.equals(replaceSpace(strToArr("a b c"), 5), "a%20b%20c".toCharArray()); | |
System.out.println("Tests Passed\n"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment