文章目录加载中
替换空格
# 1. 题目描述
请实现一个函数,把字符串中的每个空格替换成"%20"。
例如输入“We are happy.”,则输出“We%20are%20happy.”。
# 2. 解题思路
一种是正则表达式:直接使用正则表达式全局替换,这种方法取巧一些。
另一种是先计算出来替换后的字符串长度,然后逐个填写字符。这种方法的时间复杂度是$O(N)$。
# 3. 代码
/**
* 用正则表达式替换
* @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"));
本文来自心谭博客:xin-tan.com,经常更新web和算法的文章笔记,前往github查看目录归纳:github.com/dongyuanxin/blog