LeetCode 题解工作台
将句子排序
一个 句子 指的是一个序列的单词用单个空格连接起来,且开头和结尾没有任何空格。每个单词都只包含小写或大写英文字母。 我们可以给一个句子添加 从 1 开始的单词位置索引 ,并且将句子中所有单词 打乱顺序 。 比方说,句子 "This is a sentence" 可以被打乱顺序得到 "sentence…
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · string·结合·排序
答案摘要
我们先将字符串 按照空格分割,得到字符串数组 ,然后遍历数组 ,将每个单词的最后一个字符减去字符 '1',得到的结果作为单词的索引,将单词的前缀作为单词的内容,最后将单词按照索引顺序拼接起来即可。 时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 string·结合·排序 题型思路
题目描述
一个 句子 指的是一个序列的单词用单个空格连接起来,且开头和结尾没有任何空格。每个单词都只包含小写或大写英文字母。
我们可以给一个句子添加 从 1 开始的单词位置索引 ,并且将句子中所有单词 打乱顺序 。
- 比方说,句子
"This is a sentence"可以被打乱顺序得到"sentence4 a3 is2 This1"或者"is2 sentence4 This1 a3"。
给你一个 打乱顺序 的句子 s ,它包含的单词不超过 9 个,请你重新构造并得到原本顺序的句子。
示例 1:
输入:s = "is2 sentence4 This1 a3" 输出:"This is a sentence" 解释:将 s 中的单词按照初始位置排序,得到 "This1 is2 a3 sentence4" ,然后删除数字。
示例 2:
输入:s = "Myself2 Me1 I4 and3" 输出:"Me Myself and I" 解释:将 s 中的单词按照初始位置排序,得到 "Me1 Myself2 and3 I4" ,然后删除数字。
提示:
2 <= s.length <= 200s只包含小写和大写英文字母、空格以及从1到9的数字。s中单词数目为1到9个。s中的单词由单个空格分隔。s不包含任何前导或者后缀空格。
解题思路
方法一:字符串分割
我们先将字符串 按照空格分割,得到字符串数组 ,然后遍历数组 ,将每个单词的最后一个字符减去字符 '1',得到的结果作为单词的索引,将单词的前缀作为单词的内容,最后将单词按照索引顺序拼接起来即可。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
class Solution:
def sortSentence(self, s: str) -> str:
ws = [(w[:-1], int(w[-1])) for w in s.split()]
ws.sort(key=lambda x: x[1])
return ' '.join(w for w, _ in ws)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) for parsing and O(n log n) if sorting by indices, but since n <= 9, the practical runtime is constant. Space complexity is O(n) for storing words and their positions. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if the candidate efficiently extracts numeric indices from words without extra string manipulations.
- question_mark
Watch for correct placement of words in their original positions, especially when input is already partially ordered.
- question_mark
Confirm candidate handles edge cases with minimum or maximum number of words correctly.
常见陷阱
外企场景- error
Forgetting to remove the numeric suffix after sorting, resulting in incorrect output.
- error
Using unstable sorting which can mix up words with similar numeric positions.
- error
Incorrectly parsing the string, especially splitting or indexing errors on words.
进阶变体
外企场景- arrow_right_alt
Reconstruct sentences with multi-digit indices requiring robust parsing logic.
- arrow_right_alt
Handle shuffled sentences with punctuation attached to words, needing clean separation before sorting.
- arrow_right_alt
Optimize in-place sorting using index mapping instead of extra arrays for space efficiency.