0151.翻转字符串里的单词 增加Python版本实现5

This commit is contained in:
Lane Zhang
2024-10-16 14:20:41 +08:00
parent 42d84f8a7f
commit 7bbf3827d1

View File

@ -513,6 +513,29 @@ class Solution:
return "".join(result) return "".join(result)
``` ```
(版本五) 遇到空格就说明前面的是一个单词,把它加入到一个数组中。
```python
class Solution:
def reverseWords(self, s: str) -> str:
words = []
word = ''
s += ' ' # 帮助处理最后一个字词
for char in s:
if char == ' ': # 遇到空格就说明前面的可能是一个单词
if word != '': # 确认是单词,把它加入到一个数组中
words.append(word)
word = '' # 清空当前单词
continue
word += char # 收集单词的字母
words.reverse()
return ' '.join(words)
```
### Go ### Go
版本一: 版本一: