剑指offer-2:替换空格
- 方法1
上述需要向后扩充容量重新整理内存的,最好能够考虑到从尾部开始整理
class Solution {
public:
void replaceSpace(char *str,int length) {
int count = 0;
for(int i = 0; i < length; i++){
if(str[i] == ' ')
count++;
}
for(int j = length - 1; j >= 0; j--){
if(str[j] == ' ')
{
count--;
str[j + count * 2] = '%';
str[j + count * 2 + 1] = '2';
str[j + count * 2 + 2] = '0';
}
else
str[j + count * 2] = str[j];
}
}
};
- 方法2
遍历容器的方法 利用string可以拼接
class Solution{
public:
string replaceSpace(string &str){
string res;
for(auto x : str)
if(x == ' ')
res += "%20";
else
res += x;
return res;
}
};