给定一个字符串,将字符串中空格的替换为%20
思路:
- 先正向遍历一遍,找出有几个空格,记录在count
- 第二遍从后向前遍历,将每个字符向后移动2*count
- 每次替换一个空格count减一
//字符替换 --正向读取空格数, 反向移动字符
//str可以用[] 在面试题下不考虑是否越界;
class Solution {
public:
void replaceSpace(char *str,int length) {
int i = 0;
int num = 0;
while (i < length) {
if (str[i++] == ' ')
num++;
}
i--;
while (i >= 0) {
if (str[i] != ' ')
{
str[i+num*2] = str[i];
//num--;
} else {
num--;
str[i+2*num] = '%';
str[i+2*num+1] = '2';
str[i+2*num+2] = '0';
}
i--;
}
}
};