From c09089accda7c3cc46bc283eb63edfc9563894ab Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Sat, 6 May 2023 17:10:18 -0500 Subject: [PATCH] =?UTF-8?q?Update=20=E5=89=91=E6=8C=87Offer05.=E6=9B=BF?= =?UTF-8?q?=E6=8D=A2=E7=A9=BA=E6=A0=BC.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/剑指Offer05.替换空格.md | 34 ++++++++++++++++++++------ 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/problems/剑指Offer05.替换空格.md b/problems/剑指Offer05.替换空格.md index d86cc6dc..dbad781e 100644 --- a/problems/剑指Offer05.替换空格.md +++ b/problems/剑指Offer05.替换空格.md @@ -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