1.替换空格
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof
class Solution {
public:
string replaceSpace(string s) {
int l1 = s.length() - 1;
for (int i = 0; i <= l1; i++) {
if (s[i] == ' ') {
s += "00";
}
}//出现空格就加两个长度
int l2 = s.length() - 1;
if (l2 <= l1) {
return s;
}//没有空格的情况
for (int i = l1; i >= 0; i--) {
char c = s[i];
if (c == ' ') {
s[l2--] = '0';
s[l2--] = '2';
s[l2--] = '%';
} else {
s[l2--] = c;
}
}
return s;
}
};
京公网安备 11010502036488号