一、原地替换(resize字符串)
class Solution {
public:
string replaceSpace(string s) {
int count = 0;
int n =s.size();
for(int i=0;i<n;i++)
{
if(s[i]==' ')
count +=3;
else
count++;
}
s.resize(count);
for(int i =count-1,j=n-1;j<i;i--,j--)
{
if(s[j]==' ')
{
s[i] = '0';
s[i-1] = '2';
s[i-2] = '%';
i-=2;
}
else
s[i]=s[j];
}
return s;
}
};
二、定义新字符串
class Solution {
public:
string replaceSpace(string s) {
string s1;
for(int i = 0;i < s.size();i++)
{
if(s[i] == ' ')
{
s1 += "%20";
}
else
{
s1 += s[i];
}
}
return s1;
}
};