文章目录
- 题目要求
- 解题思路
- 方法一:双指针
- 方法二:python字符串操作
- 知识点
题目要求
输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"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) - 1while i >= 0:while i >= 0 and s[i] != ' ':i -= 1res.append(s[i+1: j+1])while s[i] == ' ':i -= 1j = 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()方法










