给定一个字符串,逐个翻转字符串中的每个单词。
示例 1:
输入: “the sky is blue”
输出: “blue is sky the”
示例 2:
输入: " hello world! "
输出: “world! hello”
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
1.双指针
倒序遍历字符串 s,记录单词左右索引边界 。再从后往前确定每一个单词的边界,则将其添加至新的一个列表 。最后将单词列表拼接为字符串。
ps.因为字符串开头结尾有空格,需要一开始去掉。
class Solution:
def reverseWords(self, s: str) -> str:
s = s.strip()
i = j = len(s)-1
res = []
while i>=0:
while i>=0 and s[i]!=' ':
i -= 1
res.append(s[i+1:j+1])
while s[i]==' ':
i -= 1
j = i
return ' '.join(res)
2.调函数库
调用split()分好每个块,之后倒叙排好。再用’ '作为标准jion()成新的字符串。
class Solution:
def reverseWords(self, s: str) -> str:
return ' '.join(s.split()[::-1])
3.正则
class Solution:
def reverseWords(self, s: str) -> str:
return ' '.join(re.findall(r'[\S]+',s)[::-1])