Idea: This
question is to count the number of spaces, and then replace it with the total string length of %20, using double pointers. Just start from the back and traverse forward, depending on the code.
Code:
class Solution {
public:
string replaceSpace(string s) {
int tmp = 0;
for(auto &i:s){
if(i==' ') ++tmp;
}
int len = s.size() + tmp*2;
int i = s.size()-1;
int j = len-1;
s.resize(len);
while(i>=0){
if(s[i]!=' '){
s[j]=s[i];
--i;
--j;
}else{
--i;
s[j--] ='0';
s[j--] ='2';
s[j--] ='%';
}
}
s[len] = '\0';
return s;
}
};