mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
0151.翻转字符串里的单词 增加Python版本实现5
This commit is contained in:
@ -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:
|
||||
|
||||
版本一:
|
||||
|
Reference in New Issue
Block a user