[LeetCode] 2129. Capitalize the Title

You are given a string title consisting of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that:
If the length of the word is 1 or 2 letters, change all letters to lowercase.
Otherwise, change the first letter to uppercase and the remaining letters to lowercase.
Return the capitalized title.

Example 1:
Input: title = “capiTalIze tHe titLe”
Output: “Capitalize The Title”
Explanation:
Since all the words have a length of at least 3, the first letter of each word is uppercase, and the remaining letters are lowercase.

Example 2:
Input: title = “First leTTeR of EACH Word”
Output: “First Letter of Each Word”
Explanation:
The word “of” has length 2, so it is all lowercase.
The remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.

Example 3:
Input: title = “i lOve leetcode”
Output: “i Love Leetcode”
Explanation:
The word “i” has length 1, so it is lowercase.
The remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.

Constraints:
1 <= title.length <= 100
title consists of words separated by a single space without any leading or trailing spaces.
Each word consists of uppercase and lowercase English letters and is non-empty.

将标题首字母大写。

给你一个字符串 title ,它由单个空格连接一个或多个单词组成,每个单词都只包含英文字母。请你按以下规则将每个单词的首字母 大写 :
如果单词的长度为 1 或者 2 ,所有字母变成小写。
否则,将单词首字母大写,剩余字母变成小写。
请你返回 大写后 的 title 。

思路

判断每个单词的长度,然后根据情况做不同的操作。考察对字符串的拼接和大小写的转换。

复杂度

时间O(n)
空间O(n) - stringbuilder

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public String capitalizeTitle(String title) {
String[] words = title.split(" ");
StringBuilder sb = new StringBuilder();
for (String word : words) {
int n = word.length();
if (n <= 2) {
sb.append(word.toLowerCase());
} else {
sb.append(word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase());
}
sb.append(" ");
}
return sb.toString().trim();
}
}

[LeetCode] 2129. Capitalize the Title
https://shurui91.github.io/posts/76471328.html
Author
Aaron Liu
Posted on
March 10, 2024
Licensed under