Leetcode 2129. Capitalize the Title
Problem Statement
You are given a string title
which consists of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by following the rules below:
- Return the string such that:
- For a single letter word, it should be kept in lowercase.
- For words with more than two letters, the first character is uppercase, and the rest are lowercase.
- Return the capitalized title as a string.
Clarifying Questions
- Are there any non-alphabetic characters in the input string?
- No, the input string consists only of English letters and spaces.
- Can the input string be empty?
- Yes, we need to handle the case where the input string is empty.
- Should leading or trailing whitespaces be removed?
- The input string does not contain leading or trailing whitespaces according to the problem description.
- What about words with exactly two letters?
- Words with exactly two letters should be converted to lowercase.
Code
public class Solution {
public String capitalizeTitle(String title) {
// Split the input title into words
String[] words = title.split(" ");
StringBuilder result = new StringBuilder();
// Iterate through each word
for (String word : words) {
if (word.length() > 2) {
// Capitalize first letter and set rest to lowercase
result.append(Character.toUpperCase(word.charAt(0)))
.append(word.substring(1).toLowerCase());
} else {
// Convert entire word to lowercase
result.append(word.toLowerCase());
}
// Append a space after each word
result.append(" ");
}
// Trim the trailing space and return the result
return result.toString().trim();
}
}
Strategy
- Splitting the Input: We first split the input string by spaces to get individual words.
- Processing Each Word:
- If the word length is greater than 2, capitalize the first letter and make the rest lowercase.
- If the word length is 2 or less, convert the entire word to lowercase.
- Concatenation:
- Append each processed word to a
StringBuilder
.
- Append a space after each word.
- Trimming the Result: After processing all words, trim the trailing space to produce the correct output format.
Time Complexity
- Splitting the String: O(n), where n is the length of the input string.
- Iterating Through Words: O(w) * O(k), where w is the number of words, and k is the average length of the words. In total, this process also takes O(n) because each character is processed once.
- Overall Time Complexity: O(n), where n is the length of the input string. This is efficient and scales well with input size.
This approach ensures that we handle all the given requirements within optimal time complexity.
Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI
-
Got blindsided by a question you didn’t expect?
-
Spend too much time studying?
-
Or simply don’t have the time to go over all 3000 questions?