Problem
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
or2
letters, change all letters to lowercase. - Otherwise, change the first letter to uppercase and the remaining letters to lowercase.
Return the capitalized title
.
Examples
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.
Solution
Method 1 - Split the string
We need to capitalize each word in the given string title
based on its length. If the word is 1 or 2 characters long, we’ll convert the entire word to lowercase. Otherwise, we’ll capitalize the first character and convert the rest to lowercase.
Here is the approach:
- Split the string
title
into words using the space delimiter. - For each word, check its length:
- If the length is 1 or 2, convert the word to lowercase.
- If the length is greater than 2, convert the first character to uppercase and the rest to lowercase.
- Join the processed words back into a single string with spaces in between.
- Return the resulting string.
Code
Java
class Solution {
public String capitalizeTitle(String title) {
String[] words = title.split(" ");
StringBuilder ans = new StringBuilder();
for (String word : words) {
if (word.length() <= 2) {
ans.append(word.toLowerCase());
} else {
ans.append(Character.toUpperCase(word.charAt(0)))
.append(word.substring(1).toLowerCase());
}
ans.append(" ");
}
// Remove the trailing space
return ans.toString().trim();
}
}
Python
class Solution:
def capitalizeTitle(self, title: str) -> str:
words: List[str] = title.split()
ans: List[str] = []
for word in words:
if len(word) <= 2:
ans.append(word.lower())
else:
ans.append(word[0].upper() + word[1:].lower())
return " ".join(ans)
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of the stringtitle
. This is because we have to traverse through each character in the string to process it. - 🧺 Space complexity:
O(n)
. This is because we are storing the processed words in a list and the final joined string.