方法一:
class Solution:
# s 源字符串
def replaceSpace(self, s):
return s.replace(' ','%20')
方法二:这是discuss看到的一个大佬的写法,代码能力一流,值得学习
class Solution {
public:
void replaceSpace(char *str,int length) {
string s(str);
int i=0;
while((i=s.find(' ',i))>-1){
s.erase(i,1);
s.insert(i,"%20");
}
auto ret=s.c_str();
strcpy(str,ret);
}
};
方法三:自己最开始的想法实现,由于C++手生,先从简单的练起。
class Solution {
public:
void replaceSpace(char *str,int length) {
int i = 0;
while(str[i] != '\0'){
if (str[i] == ' '){
for(int j = length; j > i; j--){
str[j+2] = str[j];
}
str[i] = '%';
str[i+1] = '2';
str[i+2] = '0';
}
i++;
}
}
};
方法四:求出空格数,把str指向的空间容量扩大到能接纳替换后的字符串容量大小,使用realloc函数,然后从原始字符串的尾部把字符一个一个复制到扩容字符串的尾部,遇到空格就替换,只有从尾部开始才能保证数据不被覆盖。
class Solution {
public:
void replaceSpace(char *str,int length) {
int cnt = 0;
int i = length - 1;
for (int i = 0; i < length; cnt += (str[i++] == ' '));
str = (char *)realloc(str, length += 2 * cnt);
for (int j = length - 1; i >= 0; i--) {
if (str[i] != ' ')
str[j--] = str[i];
else
str[j] = '0', str[j - 1] = '2', str[j - 2] = '%', j -= 3;
}
}
};