LeetCode 3368: First Letter Capitalization Solution
Master LeetCode problem 3368 (First Letter Capitalization), a hard 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.
3368. First Letter Capitalization
Problem Explanation
Explanation
To capitalize the first letter of each word in a given string, we can iterate over the characters of the string and capitalize the first letter of each word whenever we encounter a non-space character following a space character or at the start of the string. We can achieve this by keeping track of the current word boundary and capitalizing the character accordingly. The time complexity of this approach is O(n) where n is the length of the input string, and the space complexity is O(1).
Solution Code
class Solution {
public String capitalizeFirstLetter(String s) {
StringBuilder result = new StringBuilder();
boolean capitalize = true;
for (char c : s.toCharArray()) {
if (Character.isWhitespace(c)) {
capitalize = true;
} else if (capitalize) {
result.append(Character.toUpperCase(c));
capitalize = false;
} else {
result.append(c);
}
}
return result.toString();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3368 (First Letter Capitalization)?
This page provides optimized solutions for LeetCode problem 3368 (First Letter Capitalization) 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 3368 (First Letter Capitalization)?
The time complexity for LeetCode 3368 (First Letter Capitalization) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3368 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3368 in Java, C++, or Python.