LeetCode 题解工作台

反转字符串中的单词 III

给定一个字符串 s ,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。 示例 1: 输入: s = "Let's take LeetCode contest" 输出: "s'teL ekat edoCteeL tsetnoc" 示例 2: 输入: s = "Mr Ding" 输…

category

2

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 双·指针·invariant

bolt

答案摘要

我们可以将字符串 按照空格分割成单词数组 ,然后将每个单词反转后再拼接成字符串。 时间复杂度 ,空间复杂度 。其中 为字符串 的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个字符串 s ,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。

 

示例 1:

输入:s = "Let's take LeetCode contest"
输出:"s'teL ekat edoCteeL tsetnoc"

示例 2:

输入: s = "Mr Ding"
输出:"rM gniD"

 

提示:

  • 1 <= s.length <= 5 * 104
  • s 包含可打印的 ASCII 字符。
  • s 不包含任何开头或结尾空格。
  • s 里 至少 有一个词。
  • s 中的所有单词都用一个空格隔开。
lightbulb

解题思路

方法一:模拟

我们可以将字符串 s\textit{s} 按照空格分割成单词数组 words\textit{words},然后将每个单词反转后再拼接成字符串。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为字符串 s\textit{s} 的长度。

1
2
3
4
class Solution:
    def reverseWords(self, s: str) -> str:
        return " ".join(t[::-1] for t in s.split())
speed

复杂度分析

指标
时间\mathcal{O}(N)
空间\mathcal{O}(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for understanding of two-pointer techniques and their application in string manipulation.

  • question_mark

    Evaluate the candidate's ability to optimize space usage with in-place operations.

  • question_mark

    Test for edge case handling, such as a single-word string or a string with multiple spaces.

warning

常见陷阱

外企场景
  • error

    Misidentifying word boundaries and reversing characters across spaces.

  • error

    Not handling strings with a single word or very short input correctly.

  • error

    Forgetting to manage the space complexity by using in-place modification.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Handle strings with multiple spaces between words or trailing spaces.

  • arrow_right_alt

    Implement the solution with a different space-time trade-off (e.g., using a stack).

  • arrow_right_alt

    Expand the problem to reverse a sentence as a whole while reversing words.

help

常见问题

外企场景

反转字符串中的单词 III题解:双·指针·invariant | LeetCode #557 简单