* 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.
* (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"
*/
做CareerCup1.4的时候发现一个问题,下面是我的代码:
import java.util.Scanner;
public class ReplaceSpace1_4 {
/*
* The Question required to implements this Q in place, which means the parameter of the method
should be char[] rather than String, and cannot use another char[] inside the method.
* Because the length of the char[] is fixed when initial char[]
So we initial the char[] have enough space to store char.
* 1. count the number of spaces in the input string except the space at the end of char[]
2. calculate the new length needed after replace the space with '%20'
3. Traverse the char[] from the tail(the new length location rather than the whole char[])
to the front to avoid rewrite
* Time Complexity: O(n)
Space Complexity: O(1)
*/
private static void ReplaceSpace1(char[] str, int length) {
int count = 0; // count the number of spaces(except the space at the end of char[])
int temp = 0; // temporary count the number of successive spaces
// the last temp will count the number of space at the end of char[]
int num;
for (num = 0; num < length; num++) {
if (str[num] == ' ') {
temp++;
} else {
count = count + temp;
temp = 0; //spaces here are not at the end of the input string, set the temp to 0
}
}
int oldLength = num - temp; //length except the spaces at the end of char[]
int newLength = oldLength + (count << 1); //calculate the target length of the output char[]
for (int i = oldLength - 1; i >= 0; i--) {
if (str[i] == ' ') { //changes begin from the char[newLength - 1]
str[newLength - 1] = '0';
str[newLength - 2] = '2';
str[newLength - 3] = '%';
newLength = newLength - 3;
} else {
str[--newLength] = str[i];
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a string: ");
while (input.hasNextLine()) {
char[] str = new char[inputStr.length() * 3];
for (int i = 0; i < inputStr.length(); i++) {
str[i] = inputStr.charAt(i);
}
ReplaceSpace1(str, inputStr.length());
System.out.print("String after replace all the spaces: ");
for (int i = 0; str[i] != '\0'; i++) {
System.out.print(str[i]);
}
System.out.println();
System.out.println("Please enter another string: ");