LeetCode 186. 翻转字符串里的单词 II

186. 翻转字符串里的单词 II

Difficulty: 中等

给定一个字符串,逐个翻转字符串中的每个单词。

示例:

输入: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
输出: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]

注意:

  • 单词的定义是不包含空格的一系列字符
  • 输入字符串中不会包含前置或尾随的空格
  • 单词与单词之间永远是以单个空格隔开的

进阶:使用 O(1) 额外空间复杂度的原地解法。

Solution

这道题跟旋转数组是同一类型的题目,解法也相同,参考:LeetCode 189. 旋转数组 - swordspoet - 博客园

class Solution:
    def reverseWords(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        self.reverse(s, 0, len(s)-1)
        start = 0
        for i, e in enumerate(s):
            if e == " ":
                self.reverse(s, start, i-1)
                start = i + 1
            elif i == len(s) - 1:
                self.reverse(s, start, i)
        
    def reverse(self, l, start, end):
        while start < end:
            l[start], l[end] = l[end], l[start]
            start += 1
            end -= 1
posted @ 2021-03-27 14:21  swordspoet  阅读(103)  评论(0编辑  收藏  举报