2020-2-23
链接:剑指offer_牛客网_替换空格
题目描述:
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路:
- 从后往前插入(从前往后插入,这样移动的次数多不建议)
- 先计算替换后的字符串的长度。
class Solution {
public:
void replaceSpace(char *str,int length) {
int len = 0; //旧字符串的长度
int n = 0; //空格的个数
//遍历一遍字符串
int i = 0;
while(str[i] != '\0'){
len++;
if(str[i] == ' '){
n++;
}
i++;
}
int newlen = len + n*2; //新字符串的长度
if(newlen > length){ //如果新字符串的长度大于length就不能进行替换
return ;
}
int pold = len; //不减1,是因为还有'\0'
int pnew = newlen;
while(pold > -1 && pnew > pold){
if(str[pold] == ' '){
str[pnew--] = '0';
str[pnew--] = '2';
str[pnew--] = '%';
pold--;//不管是if还是elsr都要把pOldlength前移
}
else{
str[pnew--] = str[pold--];//不管是if还是elsr都要把pOldlength前移
}
}
}
};