Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add second js solutions for lcof problems 05 #357

Merged
merged 1 commit into from
Apr 22, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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