From 7ae65550db141a1bb6f3e537d027d25b5b24b1d6 Mon Sep 17 00:00:00 2001 From: SwordsmanYao Date: Fri, 23 Jul 2021 15:26:04 +0800 Subject: [PATCH] =?UTF-8?q?[=E5=89=91=E6=8C=87Offer05.=E6=9B=BF=E6=8D=A2?= =?UTF-8?q?=E7=A9=BA=E6=A0=BC]=20=E6=B7=BB=E5=8A=A0=20javaScript=20?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/剑指Offer05.替换空格.md | 39 ++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) 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)