剑指 Offer 05. 替换空格 - 力扣(LeetCode)
class Solution {
public:
string replaceSpace(string s) {
string res;
for(auto &c : s){
if(isspace(c)) res += "%20";
else res += c;
}
return res;
}
};
如果要原地修改,就需要考虑到值的覆盖问题,可以使用逆序操作:
class Solution {
public:
string replaceSpaces(string S, int length) {
int idx = S.size()-1;
for(int i = length-1; i >= 0; --i){
if(isspace(S[i])){
S[idx--] = '0';
S[idx--] = '2';
S[idx--] = '%';
}else
S[idx--] = S[i];
}
return std::move(S.substr(idx+1));
}
};