mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
[剑指Offer05.替换空格] 添加 javaScript 代码
This commit is contained in:
@ -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)
|
||||
|
Reference in New Issue
Block a user