LeetCode 2129: Capitalize the Title Solution
Master LeetCode problem 2129 (Capitalize the Title), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2129. Capitalize the Title
Problem Explanation
Explanation
We can solve this problem by iterating over each word in the input string. For each word, we check its length and then capitalize it accordingly. If the length is 1 or 2, we convert the word to lowercase. If the length is 3 or more, we capitalize the first letter and convert the rest to lowercase. We repeat this process for all words in the input string to obtain the final capitalized title.
- Time complexity: O(n), where n is the length of the input string.
- Space complexity: O(n), to store the final capitalized title.
Solution Code
class Solution {
public String capitalizeTitle(String title) {
String[] words = title.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.length; i++) {
if (words[i].length() <= 2) {
sb.append(words[i].toLowerCase());
} else {
sb.append(Character.toUpperCase(words[i].charAt(0)));
sb.append(words[i].substring(1).toLowerCase());
}
if (i < words.length - 1) {
sb.append(" ");
}
}
return sb.toString();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2129 (Capitalize the Title)?
This page provides optimized solutions for LeetCode problem 2129 (Capitalize the Title) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2129 (Capitalize the Title)?
The time complexity for LeetCode 2129 (Capitalize the Title) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2129 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2129 in Java, C++, or Python.