diff --git a/problems/剑指Offer05.替换空格.md b/problems/剑指Offer05.替换空格.md index 49c2c223..3e4e3631 100644 --- a/problems/剑指Offer05.替换空格.md +++ b/problems/剑指Offer05.替换空格.md @@ -245,6 +245,45 @@ class Solution(object): ``` +javaScript: +```js +/** + * @param {string} s + * @return {string} + */ + var replaceSpace = function(s) { + // 字符串转为数组 + const strArr = Array.from(s); + let count = 0; + + // 计算空格数量 + for(let i = 0; i < strArr.length; i++) { + if (strArr[i] === ' ') { + count++; + } + } + + let left = strArr.length - 1; + let right = strArr.length + count * 2 - 1; + + while(left >= 0) { + if (strArr[left] === ' ') { + strArr[right--] = '0'; + strArr[right--] = '2'; + strArr[right--] = '%'; + left--; + } else { + strArr[right--] = strArr[left--]; + } + } + + // 数组转字符串 + return strArr.join(''); +}; +``` + + + ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321)