leetcode 剑指 Offer 58 - I. 翻转单词顺序

   声明:本站部分内容来自互联网,如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

18

文章目录

    • 题目要求
    • 解题思路
      • 方法一:双指针
      • 方法二: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)

知识点

  1. strip():去除首尾空格
    Python strip()方法
  2. split():去除字符串中间空格换行等符号
    Python split()方法
  3. reverse():数组反转
    Python List reverse()方法