Write a method to replace all spaces in a string with ‘%20’.
// there are actually no tricks in this problem.<pre name="code" class="cpp">// the API can be a vector<char>, however, the idea is the same.
string repaceSpaces(string input) {
// if the input length is 0, nothing to do but return.
if(input.size() == 0) return input;
// we need to count how many spaces in the input string.
int spaceNum = 0;
for(int i = 0; i < input.size(); ++i) {
if(input[i] == ' ') spaceNum++;
}
// if there is no space, return original string directly.
if(spaceNum == 0) return input;
// calculate the new size for the output string. Think about why we only need to multiple 2?
int newSize = input.size() + spaceNum * 2;
// it makes thing easier if we replace spaces backwards.
string output = "";
// note that, since we are copying from backward, we need to append the string front of the output.
// this is actually not good.... it actually slows down.....
for(int i = input.size() - 1; i >= 0; --i) {
// once we find a space, we replace it with '%20'.
if(input[i] == ' ') {
output = '0' + output;
output = '2' + output;
output = '%' + output;
// otherwise, just copy it to output.
} else {output = input[i] + output;}
}
return output;
}