Given a string of words separated by single spaces, find the length of the longest word. Return the maximum word length as an integer.
For example, in "The quick brown fox jumps", the longest word is "jumps" with length 5. In "Hello world", the longest is "Hello" with length 5. In "a bb ccc", the longest is "ccc" with length 3. An empty string returns 0.
Finding the longest word is a common text processing task used in readability analysis, typography (setting appropriate container widths), and natural language processing. The solution splits the string into words and tracks the maximum length encountered.
The algorithm splits the string by spaces into an array of words, iterates through each word, compares its length to the current maximum, and updates if longer. After processing all words, return the maximum length found.
Edge cases include an empty string (return 0), a single-word string (return its length), multiple words with the same length (return that length), and strings with leading/trailing spaces (the split handles them correctly when using space delimiter).
Example Input & Output
Longest word 'def' has 3
'eeeee' has 5 letters
Single word
Longest word 'quick' has 5 letters
Empty string
Algorithm Flow

Solution Approach
Split the string into words and track the maximum word length.
Handle the empty string case. Split the input on spaces to get an array of words. Initialize maxLen to 0. Iterate through each word; if its character count exceeds maxLen, update maxLen. Return maxLen after the loop.
Time complexity is O(n) where n is the string length. Space complexity is O(n) for the words array.
Best Answers
class Solution {
public int solution(String s) {
if(s.isEmpty())return 0;
String[] w=s.split(" ");int m=0;
for(int i=0;i<w.length;i++){if(w[i].length()>m)m=w[i].length();}
return m;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
