双指针其实就是用两个变量进行标记,在这里,i标记原始数组的尾指针,j标记扩增后的尾指针。这里关键要计算清楚扩增后数组容量,这样倒序插入,原数组与更改后数组不会重叠,重叠时即为不再有空格的时候。
class Solution {
public:
string replaceSpaces(string &str){
int len=0;
for(auto x:str)
if(x==' ') len+=3;
else len++;//计算扩容后数组大小
int i=str.size()-1,j=len-1;
str.resize(len);
while(i>=0){
if(str[i]==' '){
str[j--]='0';
str[j--]='2';
str[j--]='%';
}
else str[j--]=str[i];
i--;
}
return str;
}
};