151. 翻转字符串里的单词
https://leetcode-cn.com/problems/reverse-words-in-a-string/
解法一:
先将原串按空格切分。然后处理格式后反转
注意开头或末尾的空格,以及连续空格,使用split
函数会切出空串''
:
>>> ' 1 2 3 '.split(' ')
['', '1', '2', '3', ''] #开头和末尾有空格
>>> '1 2 3 '.split(' ')
['1', '2', '3', '', ''] #连续空格
>>> '1 2 3'.split(' ')
['1', '', '2', '3'] #连续
class Solution:
def reverseWords(self, s: str) -> str:
l = list(filter(lambda x : x != '', s.split(' ')))
l.reverse()
return " ".join(l)
最后更新于