题目链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/
题目如下:
解一:
class Solution {
public:
string replaceSpace(string s) {
string result="";
for(auto ch:s){
if(ch==' ') result+="%20";
else result+=ch;
}
return result;
}
};
解二:双指针
class Solution {
public:
string replaceSpace(string s) {
//思路:先扩容,再从后向前依次填充
int count=0;//统计空格数量
int before=s.size();
for(auto ch:s)
if(ch==' ') count++;
s.resize(s.size()+count*2);//扩容,将' '->"%20"
int after=s.size();
for(int i=before-1,j=after-1;i<j;i--,j--){//双指针实现扩容,因为到最终i必=j,所以,不需要加判断>0
if(s[i]!=' ') s[j]=s[i];
else {
s[j]='0';s[j-1]='2';s[j-2]='%';
j=j-2;
}
}
return s;
}
};