Merge pull request #2793 from gazeldx/l0151

0151.翻转字符串里的单词 增加Python版本实现5
This commit is contained in:
程序员Carl
2024-11-21 11:46:43 +08:00
committed by GitHub

View File

@ -513,6 +513,29 @@ class Solution:
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
版本一: