难度简单123
输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. ",则输出"student. a am I"。
示例 1:
输入: "the sky is blue" 输出: "blue is sky the"
示例 2:
输入: " hello world! " 输出: "world! hello" 解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
示例 3:
输入: "a good example" 输出: "example good a" 解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
方法一:逆序+深拷贝
class Solution:
def reverseWords(self, s: str) -> str:
alist=s.split(" ")
blist=copy.deepcopy(alist)
for i in alist:
if not i:
blist.remove(i)
b=blist[::-1]
return " ".join(b)
方法二:双指针
class Solution:
def reverseWords(self, s: str) -> str:
s=s.strip() #删除首尾空格
n=len(s)-1
a,b=n,n
res=[]
while a>=0:
while s[a]!=" " and a>=0:
a=a-1
res.append(s[a+1:b+1])
while s[a]==" ":
a=a-1
b=a
return " ".join(res)
这篇博客介绍了如何使用Python实现字符串中单词顺序的翻转。提供了两种方法,一种是通过逆序加深拷贝,另一种是利用双指针技巧。示例展示了如何处理包含空格的输入字符串,确保翻转后的字符串符合要求。
256

被折叠的 条评论
为什么被折叠?



