LeetCode 题解工作台

重新排列句子中的单词

「句子」是一个用空格分隔单词的字符串。给你一个满足下述格式的句子 text : 句子的首字母大写 text 中的每个单词都用单个空格分隔。 请你重新排列 text 中的单词,使所有单词按其长度的升序排列。如果两个单词的长度相同,则保留其在原句子中的相对顺序。 请同样按上述格式返回新的句子。 示例 1…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · string·结合·排序

bolt

答案摘要

将 `text` 按空格切分为字符串数组 `words`,并将 `words[0]` 转为小写。然后对 `words` 进行排序(这里需要确保长度相同的情况下,相对顺序保持不变,因此是一种稳定排序)。 排完序后,对 `words[0]` 首字母转为大写。最后将 `words` 所有字符串用空格拼接成一个字符串。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 string·结合·排序 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

「句子」是一个用空格分隔单词的字符串。给你一个满足下述格式的句子 text :

  • 句子的首字母大写
  • text 中的每个单词都用单个空格分隔。

请你重新排列 text 中的单词,使所有单词按其长度的升序排列。如果两个单词的长度相同,则保留其在原句子中的相对顺序。

请同样按上述格式返回新的句子。

 

示例 1:

输入:text = "Leetcode is cool"
输出:"Is cool leetcode"
解释:句子中共有 3 个单词,长度为 8 的 "Leetcode" ,长度为 2 的 "is" 以及长度为 4 的 "cool" 。
输出需要按单词的长度升序排列,新句子中的第一个单词首字母需要大写。

示例 2:

输入:text = "Keep calm and code on"
输出:"On and keep calm code"
解释:输出的排序情况如下:
"On" 2 个字母。
"and" 3 个字母。
"keep" 4 个字母,因为存在长度相同的其他单词,所以它们之间需要保留在原句子中的相对顺序。
"calm" 4 个字母。
"code" 4 个字母。

示例 3:

输入:text = "To be or not to be"
输出:"To be or to be not"

 

提示:

  • text 以大写字母开头,然后包含若干小写字母以及单词间的单个空格。
  • 1 <= text.length <= 10^5
lightbulb

解题思路

方法一:排序

text 按空格切分为字符串数组 words,并将 words[0] 转为小写。然后对 words 进行排序(这里需要确保长度相同的情况下,相对顺序保持不变,因此是一种稳定排序)。

排完序后,对 words[0] 首字母转为大写。最后将 words 所有字符串用空格拼接成一个字符串。

时间复杂度 O(nlogn)O(n\log n)

1
2
3
4
5
6
7
8
class Solution:
    def arrangeWords(self, text: str) -> str:
        words = text.split()
        words[0] = words[0].lower()
        words.sort(key=len)
        words[0] = words[0].title()
        return " ".join(words)
speed

复杂度分析

指标
时间complexity is O(n log n) where n is the number of words due to sorting, and space complexity is O(n) for storing words and their indices. The approach handles up to 10^5 characters efficiently while maintaining stable ordering for ties.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Asks how you maintain original word order when lengths are equal.

  • question_mark

    Checks if your solution handles capitalization correctly after sorting.

  • question_mark

    Probes understanding of stable sorting and tracking original indices.

warning

常见陷阱

外企场景
  • error

    Forgetting to preserve original order for words of the same length.

  • error

    Not capitalizing the first word or altering case of other words incorrectly.

  • error

    Using inefficient methods that exceed time limits for large sentences.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Rearranging words in descending length order instead of ascending.

  • arrow_right_alt

    Ignoring capitalization rules and returning all lowercase sentence.

  • arrow_right_alt

    Sorting words alphabetically only when lengths are equal instead of using original positions.

help

常见问题

外企场景

重新排列句子中的单词题解:string·结合·排序 | LeetCode #1451 中等