题目链接:https://leetcode.cn/problems/reverse-words-in-a-string/description/

核心方法:双指针

class Solution:
    def reverseWords(self, s: str) -> str:
        words = s.split()

        left,right = 0,len(words)-1
        while left<right:
            words[left],words[right] = words[right],words[left]
            left += 1
            right -=1

        return ' '.join(words)
  1. s.split() 的使用

    • split() 方法默认会按照任意空白字符(包括空格、制表符、换行符等)进行分割,并且会忽略连续的空白字符。

    • 这意味着无论是多个空格(如 "a good example")还是字符串前后的空格(如 " hello world! "),split() 都能正确地将单词提取出来,而不会包含多余的空格。

  • 示例 1

    • 输入: "the sky is blue"

    • split() 后: ["the", "sky", "is", "blue"]

    • 反转后: ["blue", "is", "sky", "the"]

    • join() 后: "blue is sky the"

  • 示例 2

    • 输入: " hello world! "

    • split() 后: ["hello", "world!"](前后空格被忽略)

    • 反转后: ["world!", "hello"]

    • join() 后: "world! hello"

  • 示例 3

    • 输入: "a good example"

    • split() 后: ["a", "good", "example"](连续空格被忽略)

    • 反转后: ["example", "good", "a"]

    • join() 后: "example good a"