LeetCode 题解工作台
将标题首字母大写
给你一个字符串 title ,它由单个空格连接一个或多个单词组成,每个单词都只包含英文字母。请你按以下规则将每个单词的首字母 大写 : 如果单词的长度为 1 或者 2 ,所有字母变成小写。 否则,将单词首字母大写,剩余字母变成小写。 请你返回 大写后 的 title 。 示例 1: 输入: titl…
1
题型
6
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
直接模拟,按空格切分字符串,得到每个单词,再按题目转大小写。最后用空格连接每个单词。 时间复杂度 ,空间复杂度 。其中 是字符串 `title` 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
给你一个字符串 title ,它由单个空格连接一个或多个单词组成,每个单词都只包含英文字母。请你按以下规则将每个单词的首字母 大写 :
- 如果单词的长度为
1或者2,所有字母变成小写。 - 否则,将单词首字母大写,剩余字母变成小写。
请你返回 大写后 的 title 。
示例 1:
输入:title = "capiTalIze tHe titLe" 输出:"Capitalize The Title" 解释: 由于所有单词的长度都至少为 3 ,将每个单词首字母大写,剩余字母变为小写。
示例 2:
输入:title = "First leTTeR of EACH Word" 输出:"First Letter of Each Word" 解释: 单词 "of" 长度为 2 ,所以它保持完全小写。 其他单词长度都至少为 3 ,所以其他单词首字母大写,剩余字母小写。
示例 3:
输入:title = "i lOve leetcode" 输出:"i Love Leetcode" 解释: 单词 "i" 长度为 1 ,所以它保留小写。 其他单词长度都至少为 3 ,所以其他单词首字母大写,剩余字母小写。
提示:
1 <= title.length <= 100title由单个空格隔开的单词组成,且不含有任何前导或后缀空格。- 每个单词由大写和小写英文字母组成,且都是 非空 的。
解题思路
方法一:模拟
直接模拟,按空格切分字符串,得到每个单词,再按题目转大小写。最后用空格连接每个单词。
时间复杂度 ,空间复杂度 。其中 是字符串 title 的长度。
class Solution:
def capitalizeTitle(self, title: str) -> str:
words = [w.lower() if len(w) < 3 else w.capitalize() for w in title.split()]
return " ".join(words)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) where n is the length of the title, since each character is visited once. Space complexity is O(n) for storing the split words and the result string. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
They may ask if your solution handles single-letter words correctly.
- question_mark
They may probe how your solution deals with words exactly two characters long.
- question_mark
Expect questions on edge cases like all uppercase or all lowercase input.
常见陷阱
外企场景- error
Incorrectly capitalizing words with length 1 or 2.
- error
Failing to lowercase letters after the first character for longer words.
- error
Not preserving the original word order when joining the words back.
进阶变体
外企场景- arrow_right_alt
Allowing punctuation within words and capitalizing based on alphabetic characters only.
- arrow_right_alt
Ignoring case of the original input entirely before applying rules.
- arrow_right_alt
Applying the same rules to hyphenated words as separate words.