mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
Merge pull request #2726 from QinWeijia111/master
Update 0151.翻转字符串里的单词.md
This commit is contained in:
@ -475,7 +475,45 @@ class Solution:
|
||||
words = words[::-1] # 反转单词
|
||||
return ' '.join(words) #列表转换成字符串
|
||||
```
|
||||
(版本四) 将字符串转换为列表后,使用双指针去除空格
|
||||
```python
|
||||
class Solution:
|
||||
def single_reverse(self, s, start: int, end: int):
|
||||
while start < end:
|
||||
s[start], s[end] = s[end], s[start]
|
||||
start += 1
|
||||
end -= 1
|
||||
|
||||
def reverseWords(self, s: str) -> str:
|
||||
result = ""
|
||||
fast = 0
|
||||
# 1. 首先将原字符串反转并且除掉空格, 并且加入到新的字符串当中
|
||||
# 由于Python字符串的不可变性,因此只能转换为列表进行处理
|
||||
s = list(s)
|
||||
s.reverse()
|
||||
while fast < len(s):
|
||||
if s[fast] != " ":
|
||||
if len(result) != 0:
|
||||
result += " "
|
||||
while s[fast] != " " and fast < len(s):
|
||||
result += s[fast]
|
||||
fast += 1
|
||||
else:
|
||||
fast += 1
|
||||
# 2.其次将每个单词进行翻转操作
|
||||
slow = 0
|
||||
fast = 0
|
||||
result = list(result)
|
||||
while fast <= len(result):
|
||||
if fast == len(result) or result[fast] == " ":
|
||||
self.single_reverse(result, slow, fast - 1)
|
||||
slow = fast + 1
|
||||
fast += 1
|
||||
else:
|
||||
fast += 1
|
||||
|
||||
return "".join(result)
|
||||
```
|
||||
### Go:
|
||||
|
||||
版本一:
|
||||
|
Reference in New Issue
Block a user