题目要求
输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. “,则输出"student. a am I”。
解题思路
方法一:双指针
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
# 去除首尾空格
s = s.strip()
res = []
# 定义双指针
i, j = len(s) - 1, len(s) - 1
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)
方法二:python字符串操作
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
# 去除首尾空格
s = s.strip()
# 去除中间空格换行等符号
temp = s.split()
# 数组反转
temp.reverse()
# 以空格为分隔将列表转为字符串输出
return ' '.join(temp)
知识点
- strip():去除首尾空格
Python strip()方法 - split():去除字符串中间空格换行等符号
Python split()方法 - reverse():数组反转
Python List reverse()方法