01-替换空格
ALEX CODE PARK 2020-02-05
算法
字符串
# 题目描述
请实现一个函数,把字符串中的每个空格替换成"%20"。 例如输入“We are happy.”,则输出“We%20are%20happy.”。
# 解题思路
一种是正则表达式:直接使用正则表达式全局替换,这种方法取巧一些。 另一种是先计算出来替换后的字符串长度,然后逐个填写字符。这种方法的时间复杂度是$O(N)$。
# 代码实现
/**
* 用正则表达式替换
* @param {String} str
*/
function repalceEmpty1(str) {
const re = / /g;
return str.replace(re, "%20");
}
/**
* 将空格替换为 %20
* @param {String} arr
*/
function repalceEmpty2(str) {
str = str.split("");
let count = 0,
i = 0,
j = 0;
for (let i = 0; i < str.length; ++i) {
str[i] === " " && ++count;
}
let length = str.length + count * 2; // 新的字符串的长度:%20比空格长度多2
let result = new Array(length);
while (i < result.length) {
if (str[j] === " ") {
result[i++] = "%";
result[i++] = "2";
result[i++] = "0";
j++;
} else {
result[i++] = str[j++];
}
}
return result.join("");
}
/**
* 测试代码
*/
console.log(repalceEmpty1("We are happy"));
console.log(repalceEmpty2("We are happy"));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# 我的解法
indexof 时间复杂度未知
function replaceSpace(str) {
arr = str.split("");
start = arr.indexOf(" ");
while (start != -1) {
console.log(start);
arr.splice(start, 1, "%20");
start = arr.indexOf(" ");
}
return arr.join("");
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
foreach O(n)
function replaceSpace(str) {
let res = [];
str.split("").forEach(a => {
return a == " " ? res.push("%20") : res.push(a);
});
return res.join("");
}
1
2
3
4
5
6
7
2
3
4
5
6
7