Skip to content

151.反转字符串中的单词

two pointers, https://leetcode.cn/problems/reverse-words-in-a-string/

给你一个字符串 s ,请你反转字符串中 单词 的顺序。

单词 是由非空格字符组成的字符串。s 中使用至少一个空格将字符串中的 单词 分隔开。

返回 单词 顺序颠倒且 单词 之间用单个空格连接的结果字符串。

注意:输入字符串 s中可能会存在前导空格、尾随空格或者单词间的多个空格。返回的结果字符串中,单词间应当仅用单个空格分隔,且不包含任何额外的空格。

示例 1:

输入:s = "the sky is blue"
输出:"blue is sky the"

示例 2:

输入:s = "  hello world  "
输出:"world hello"
解释:反转后的字符串中不能存在前导空格和尾随空格。

示例 3:

输入:s = "a good   example"
输出:"example good a"
解释:如果两个单词间有多余的空格,反转后的字符串需要将单词间的空格减少到仅有一个。

提示:

  • 1 <= s.length <= 104
  • s 包含英文大小写字母、数字和空格 ' '
  • s至少存在一个 单词

进阶:如果字符串在你使用的编程语言中是一种可变数据类型,请尝试使用 O(1) 额外空间复杂度的 原地 解法。

python
class Solution:
    def reverseWords(self, s: str) -> str:
        tokens = s.split()
        left, right = 0, len(tokens)-1
        # tokens.reverse()
        while left < right:
            tokens[left], tokens[right] = tokens[right], tokens[left]
            left += 1
            right -= 1
        
        return ' '.join(tokens)

下面代码是为了练习。也可以AC。

l = list(s.strip()) 这行代码会创建一个新的列表 l,并不会在原地修改字符串 s。在 Python 中,字符串是不可变的,因此无法直接在原地修改字符串。将字符串转换为列表是为了能够在原地修改字符顺序,但这仍然会创建一个新的列表对象。

python
from typing import List
class Solution:
    def reverseWords(self, s: str) -> str:
        # Helper function to reverse a portion of the list in place
        def reverse(l: List[str], start: int, end: int) -> None:
            while start < end:
                l[start], l[end] = l[end], l[start]
                start += 1
                end -= 1

        # Convert the string to a list of characters for in-place manipulation
        l = list(s.strip())
        n = len(l)

        # Reverse the entire list
        reverse(l, 0, n - 1)

        # Reverse each word in the reversed list
        start = 0
        for end in range(n):
            if l[end] == ' ':
                reverse(l, start, end - 1)
                start = end + 1
        reverse(l, start, n - 1)

        # Remove extra spaces between words
        slow = 0
        for fast in range(n):
            if l[fast] != ' ' or (fast > 0 and l[fast - 1] != ' '):
                l[slow] = l[fast]
                slow += 1

        # Convert the list back to a string and return
        return ''.join(l[:slow])

# 示例测试
if __name__ == "__main__":
    sol = Solution()
    print(sol.reverseWords("the sky is blue"))  # 输出: "blue is sky the"
    print(sol.reverseWords("  hello world  "))  # 输出: "world hello"
    print(sol.reverseWords("a good   example"))  # 输出: "example good a"