替换字符串的空格
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = “We are happy.”
输出:“We%20are%20happy.”
来源:力扣(LeetCode)
链接:替换字符串的空格
题记:
先遍历一遍字符串,统计这个字符串的空格数,由此我们可以得到新的字符串的总长度。每替换一个空格,字符串长度增加2。从后往前遍历,一个指针P1指向原来字符串的末尾,另一个指针P2指向新的字符串的末尾。P1向前遍历,逐个将字符复制到P2所指位置直到遇到空格,把P1向前移动一个,将字符串%20复制到P2前面
C++代码在输入""时报错
terminate called after throwing an instance of ‘std::logic_error’
what(): basic_string::_M_construct null not valid
发现是因为原书使用的是数组,但是这里使用的是字符串。因此需要注意到两点不同:
1、s的末尾不是‘\0’
2、计算空格的方法要发生改变,而且增加空格的时候必须要对s的长度进行调整,而不能像数组那样,直接移动指针。
以上两个错误不注意的话,会导致overflow。
作者:hurricane-one
class Solution {
public:
string replaceSpace(string s) {
if(s.size()==0){
return "";
}
int num_space=0,original_len=s.size()-1,i=0;
while(i<s.length()){
if(s[i] ==' '){
++num_space;
}
i++;
}
int new_len = original_len+num_space*2;
s+=string(num_space*2,' ');
int index_original=original_len;
int index_new=new_len;
while(index_original>=0 && index_new>index_original){
if(s[index_original]==' '){
s[index_new--]='0';
s[index_new--]='2';
s[index_new--]='%';
}
else{
s[index_new--]=s[index_original];
}
--index_original;
}
return s;
}
};
还有一种办法就是申请新的空间遍历一遍原字符串,当遍历到空格,就在新字符串接%20,否则就把原字符串的字符接在后面,不过这样做应该就失去了题目的意义吧,不过还是把答案贴出来:
class Solution {
public:
string replaceSpace(string s) {
string res;
for (char c : s)
if (c == ' ') res += "%20";
else res += c;
return res;
}
};