Merge pull request #1945 from ZerenZhang2022/patch-14

Update 0151.翻转字符串里的单词.md
This commit is contained in:
程序员Carl
2023-03-25 08:57:27 +08:00
committed by GitHub

View File

@ -516,6 +516,48 @@ class Solution:
return s[:ps] + s[ps:][::-1] # Must do the last step, because the last word is omit though the pointers are on the correct positions, return s[:ps] + s[ps:][::-1] # Must do the last step, because the last word is omit though the pointers are on the correct positions,
``` ```
```python
class Solution: # 使用双指针法移除空格
def reverseWords(self, s: str) -> str:
def removeextraspace(s):
start = 0; end = len(s)-1
while s[start]==' ':
start+=1
while s[end]==' ':
end-=1
news = list(s[start:end+1])
slow = fast = 0
while fast<len(news):
while fast>0 and news[fast]==news[fast-1]==' ':
fast+=1
news[slow]=news[fast]
slow+=1; fast+=1
#return "".join(news[:slow])
return news[:slow]
def reversestr(s):
left,right = 0,len(s)-1
news = list(s)
while left<right:
news[left],news[right] = news[right],news[left]
left+=1; right-=1
#return "".join(news)
return news
news = removeextraspace(s)
news.append(' ')
fast=slow=0
#print(news)
while fast<len(news):
while news[fast]!=' ':
fast+=1
news[slow:fast] = reversestr(news[slow:fast])
# print(news[slow:fast])
fast=slow=fast+1
news2 = reversestr(news[:-1])
return ''.join(news2)
```
Go Go
```go ```go