Skip to content

Commit 4d7d0f3

Browse files
authored
feat: add second js solutions for lcof problems 05 (doocs#357)
1 parent 7f3f576 commit 4d7d0f3

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

lcof/面试题05. 替换空格/README.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ class Solution {
5858

5959
### **JavaScript**
6060

61+
- 使用字符串内置方法
62+
6163
```js
6264
/**
6365
* @param {string} s
@@ -67,6 +69,37 @@ var replaceSpace = function (s) {
6769
return s.split(" ").join("%20");
6870
};
6971
```
72+
- 使用两个指针
73+
74+
```js
75+
/**
76+
* @param {string}
77+
* @return {string}
78+
*/
79+
var replaceSpace = function(s) {
80+
s = s.split("");
81+
let emptyNum = 0;
82+
for (let i = 0; i < s.length; i++) {
83+
if (s[i] === " ") {
84+
emptyNum++;
85+
}
86+
}
87+
let p1 = s.length - 1;
88+
let p2 = p1 + 2 * emptyNum;
89+
while (p1 >= 0 && p2 > p1) {
90+
if (s[p1] === " ") {
91+
s[p2] = "0";
92+
s[--p2] = "2";
93+
s[--p2] = "%";
94+
} else {
95+
s[p2] = s[p1];
96+
}
97+
p1--;
98+
p2--;
99+
}
100+
return s.join("");
101+
};
102+
```
70103

71104
### **Go**
72105

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy