问题描述
请实现一个函数,把字符串 s
中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
限制:
0 <= s 的长度 <= 10000
解题思路
双指针,一个指向原字符串,一个指向新生成的字符串。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 | class Solution:
def replaceSpace(self, s: str) -> str:
n = len(s)
ans = [""] * 3 * n
j = 0
for i in range(n):
if s[i] == ' ':
ans[j] = '%'
j += 1
ans[j] = '2'
j += 1
ans[j] = '0'
j += 1
else:
ans[j] = s[i]
j += 1
return "".join(ans[:j])
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 | class Solution {
public:
string replaceSpace(string s) {
int n = s.size();
string ans(3 * n, ' ');
int i, j;
for (i = 0, j = 0; i < n; ++i) {
if (s[i] == ' ') {
ans[j++] = '%';
ans[j++] = '2';
ans[j++] = '0';
} else ans[j++] = s[i];
}
return ans.substr(0, j);
}
};
|
时间复杂度:\(\mathcal{O}(n)\)
空间复杂度:\(\mathcal{O}(n)\)