替换空格
题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路: 预先计算出替换后的字符串的长度, 然后从后向前复制
版本一: 没做出来, 参考书上解题思路
class Solution {
public:
void replaceSpace(char *str,int length) {
int numBef = 0;
int numAft = 0;
int numBank = 0;
int i = 0;
while ('\0' != str[i]) {
numBef++;
if (' ' == str[i]) {
numBank++;
}
i++;
}
numBef += 1;
numAft = numBef + numBank * 2;
while (0 <= numBef) {
if (' ' == str[numBef]) {
str[numAft] = '0';
str[numAft - 1] = '2';
str[numAft - 2] = '%';
numBef--;
numAft -= 3;
continue;
}
str[numAft] = str[numBef];
numBef--;
numAft--;
}
}
};
版二: 书上改了不点不点
class Solution {
public:
void replaceSpace(char *str,int length) {
if ((NULL == str) || (0 == length)) {
return;
}
int originalLength = 0;
int numberOfBank = 0;
int i = 0;
while ('\0' != str[i]) {
if (' ' == str[i]) {
numberOfBank++;
}
originalLength++;
i++;
}
int newLength = originalLength + numberOfBank * 2;
if (newLength > length) {
return;
}
int oldIndex = originalLength;
int newIndex = newLength;
while((oldIndex >= 0) && (newIndex > oldIndex)) {
if (' ' == str[oldIndex]) {
str[newIndex--] = '0';
str[newIndex--] = '2';
str[newIndex--] = '%';
}
else {
str[newIndex--] = str[oldIndex];
}
oldIndex--;
}
}
};