Skip to content

Commit

Permalink
feat: add second js solutions for lcof problems 05 (#357)
Browse files Browse the repository at this point in the history
  • Loading branch information
shuxiaotai committed Apr 22, 2021
1 parent 7f3f576 commit 4d7d0f3
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions lcof/面试题05. 替换空格/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ class Solution {

### **JavaScript**

- 使用字符串内置方法

```js
/**
* @param {string} s
Expand All @@ -67,6 +69,37 @@ var replaceSpace = function (s) {
return s.split(" ").join("%20");
};
```
- 使用两个指针

```js
/**
* @param {string}
* @return {string}
*/
var replaceSpace = function(s) {
s = s.split("");
let emptyNum = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] === " ") {
emptyNum++;
}
}
let p1 = s.length - 1;
let p2 = p1 + 2 * emptyNum;
while (p1 >= 0 && p2 > p1) {
if (s[p1] === " ") {
s[p2] = "0";
s[--p2] = "2";
s[--p2] = "%";
} else {
s[p2] = s[p1];
}
p1--;
p2--;
}
return s.join("");
};
```

### **Go**

Expand Down

0 comments on commit 4d7d0f3

Please sign in to comment.