Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 7bbf382

Browse files
committed
0151.翻转字符串里的单词 增加Python版本实现5
1 parent 42d84f8 commit 7bbf382

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

problems/0151.翻转字符串里的单词.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -513,6 +513,29 @@ class Solution:
513513

514514
return "".join(result)
515515
```
516+
517+
(版本五) 遇到空格就说明前面的是一个单词,把它加入到一个数组中。
518+
519+
```python
520+
class Solution:
521+
def reverseWords(self, s: str) -> str:
522+
words = []
523+
word = ''
524+
s += ' ' # 帮助处理最后一个字词
525+
526+
for char in s:
527+
if char == ' ': # 遇到空格就说明前面的可能是一个单词
528+
if word != '': # 确认是单词,把它加入到一个数组中
529+
words.append(word)
530+
word = '' # 清空当前单词
531+
continue
532+
533+
word += char # 收集单词的字母
534+
535+
words.reverse()
536+
return ' '.join(words)
537+
```
538+
516539
### Go:
517540

518541
版本一:

0 commit comments

Comments
 (0)