Capitalize First Letter
Given a string, capitalize the first character of each word. A word is defined as a sequence of characters separated by spaces. The rest of each word should remain in its original case.
Split the string into words by spaces, capitalize the first character of each word (convert to uppercase while keeping the rest unchanged), then join them back with spaces.
This is a common string manipulation task that tests string splitting, character access, and joining. Time complexity is O(n) and space complexity is O(n) for the result array and final string.
Edge cases include empty strings, single words, multiple consecutive spaces (treat each as separate), and already capitalized words.
Example Input & Output
Single word
Capitalize each word
Each single char word capitalized
Empty string
Already uppercase stays same
Algorithm Flow

Solution Approach
Best Answers
class Solution {
public String solution(String s) {
if(s.isEmpty())return "";String[] w=s.split(" ",-1);StringBuilder r=new StringBuilder();
for(int i=0;i<w.length;i++){
if(!w[i].isEmpty())r.append(Character.toUpperCase(w[i].charAt(0))).append(w[i].substring(1));
r.append(' ');
}return r.toString().trim();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
