1. 题目描述
请实现一个函数,把字符串中的每个空格替换成”%20”。
例如输入“We are happy.”,则输出“We%20are%20happy.”。
2. 解题思路
一种是正则表达式:直接使用正则表达式全局替换,这种方法取巧一些。
另一种是先计算出来替换后的字符串长度,然后逐个填写字符。这种方法的时间复杂度是$O(N)$。
3. 代码
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
|
function repalceEmpty1(str) { const re = / /g return str.replace(re, '%20') }
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 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'))
|