LeetCode 题解工作台
反转字符串中的单词 III
给定一个字符串 s ,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。 示例 1: 输入: s = "Let's take LeetCode contest" 输出: "s'teL ekat edoCteeL tsetnoc" 示例 2: 输入: s = "Mr Ding" 输…
2
题型
8
代码语言
3
相关题
当前训练重点
简单 · 双·指针·invariant
答案摘要
我们可以将字符串 按照空格分割成单词数组 ,然后将每个单词反转后再拼接成字符串。 时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给定一个字符串 s ,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例 1:
输入:s = "Let's take LeetCode contest" 输出:"s'teL ekat edoCteeL tsetnoc"
示例 2:
输入: s = "Mr Ding" 输出:"rM gniD"
提示:
1 <= s.length <= 5 * 104s包含可打印的 ASCII 字符。s不包含任何开头或结尾空格。s里 至少 有一个词。s中的所有单词都用一个空格隔开。
解题思路
方法一:模拟
我们可以将字符串 按照空格分割成单词数组 ,然后将每个单词反转后再拼接成字符串。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
class Solution:
def reverseWords(self, s: str) -> str:
return " ".join(t[::-1] for t in s.split())
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | \mathcal{O}(N) |
| 空间 | \mathcal{O}(1) |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.