Skip to content

Instantly share code, notes, and snippets.

@UncleGarden
Created June 21, 2014 19:38
Show Gist options
  • Save UncleGarden/f2bca2305e003bd11944 to your computer and use it in GitHub Desktop.
Save UncleGarden/f2bca2305e003bd11944 to your computer and use it in GitHub Desktop.
CareerCup 150
/**
* 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"
*
* @author Jiateng
*/
public class CC1_4 {
//Time O(n), Space O(n)
public static String replace1(String target) {
StringBuilder result = new StringBuilder();
char[] array = target.toCharArray();
for (int i = 0; i < array.length; i++) {
if (array[i] != ' ') {
result.append(array[i]);
} else {
result.append("%20");
}
}
return result.toString();
}
//Time O(n), Space O(n)
public static String replace2(String target) {
char[] array = target.toCharArray();
int len = array.length;
int spaceCount = 0;
int newLen = 0;
for (int i = 0; i < len; i++) {
if (array[i] == ' ') {
spaceCount++;
}
}
//space will be replaced by %20
newLen = len + spaceCount * 2;
char[] newArray = new char[newLen];
for (int i = len - 1; i >= 0; i--) {
if (array[i] == ' ') {
newArray[newLen - 1] = '0';
newArray[newLen - 2] = '2';
newArray[newLen - 3] = '%';
newLen -= 3;
} else {
newArray[newLen - 1] = array[i];
newLen -= 1;
}
}
return new String(newArray);
}
public static void main(String[] args) {
System.out.println(replace1(" iisfd sdfs sdfs "));
System.out.println(replace2(" iisfd sdfs sdfs "));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment