请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
思路一: 注重时间,费空间。
class Solution {
public:
string replaceSpace(string s) {
string ans = "";
for(int i = 0; i < s.size(); i++){
if(s[i] != ' ') ans += s[i];
else ans += "%20";
}
return ans;
}
};
执行用时:0 ms, 在所有 C++ 提交中击败了100.00%的用户
内存消耗:6.6 MB, 在所有 C++ 提交中击败了5.96%的用户
思路二:不额外使用空间。
class Solution {
public:
string replaceSpace(string s) {
int cnt = 0, len = s.size();
for(auto &c:s){
if(c == ' ') cnt++;
}
s.resize(len + cnt * 2);
for(int i = s.size() - 1, j = len - 1;j>=0 && i>=0; j--){
if(s[j]!=' ') s[i--] = s[j];
else{
s[i--] = '0';
s[i--] = '2';
s[i--] = '%';
}
}
return s;
}
};
执行用时:0 ms, 在所有 C++ 提交中击败了100.00%的用户
内存消耗:6.5 MB, 在所有 C++ 提交中击败了6.18%的用户