Update 剑指Offer05.替换空格.md

This commit is contained in:
jianghongcheng
2023-05-06 17:10:18 -05:00
committed by GitHub
parent dc7ac6337d
commit c09089accd

View File

@ -266,7 +266,8 @@ func replaceSpace(s string) string {
python
#### 因为字符串是不可变类型,所以操作字符串需要将其转换为列表,因此空间复杂度不可能为O(1)
#### 因为字符串是不可变类型所以操作字符串需要将其转换为列表因此空间复杂度不可能为O(1)
(版本一)转换成列表,并且添加相匹配的空间,然后进行填充
```python
class Solution:
def replaceSpace(self, s: str) -> str:
@ -291,14 +292,22 @@ class Solution:
return ''.join(res)
```
(版本二)添加空列表,添加匹配的结果
```python
class Solution:
def replaceSpace(self, s: str) -> str:
res = []
for i in range(len(s)):
if s[i] == ' ':
res.append('%20')
else:
res.append(s[i])
return ''.join(res)
```
(版本三)使用切片
```python
class Solution:
def replaceSpace(self, s: str) -> str:
# method 1 - Very rude
return "%20".join(s.split(" "))
# method 2 - Reverse the s when counting in for loop, then update from the end.
n = len(s)
for e, i in enumerate(s[::-1]):
print(i, e)
@ -307,7 +316,18 @@ class Solution:
print("")
return s
```
版本四使用join + split
```python
class Solution:
def replaceSpace(self, s: str) -> str:
return "%20".join(s.split(" "))
```
版本五使用replace
```python
class Solution:
def replaceSpace(self, s: str) -> str:
return s.replace(' ', '%20')
```
javaScript:
```js