题目
请实现一个函数,把字符串 s
中的每个空格替换成"%20"
。
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
限制:
-
解题方法
双指针
遍历数组,通过双指针记录非空格段字符串。
class Solution {
public:
string replaceSpace(string s) {
int n = s.size();
int slow = 0, fast = 0;
string out;
while(fast<n) {
if(s[fast]==' '){
out = out + s.substr(slow, fast-slow) + "%20";
slow = fast+1;
}
fast++;
}
out = out + s.substr(slow, fast-slow);
return out;
}
};
遍历数组
class Solution {
public:
string replaceSpace(string s) {
string out;
for(auto i:s) {
if(i==' ') out+="%20";
else out+=i;
}
return out;
}
};
双指针反向修改数组
先遍历数组,确定修改后的大小。
class Solution {
public:
string replaceSpace(string s) {
int count = 0;
int n = s.size();
for(auto i:s) {
if(i==' ') count++;
}
int new_n = n+count*2;
int i = n-1;
int j = new_n-1;
s.resize(new_n);
while(i>=0){
if(s[i]==' ') {
s[j] = '0';
s[j-1] = '2';
s[j-2] = '%';
j-=2;
}
else s[j] = s[i];
i--;j--;
}
return s;
}
};