Given a string s consisting of words and spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters.
Trim trailing spaces first, then find the last space character to identify the last word. Alternatively, split by spaces and take the last non-empty element.
Time complexity is O(n) and space is O(1). The solution should handle leading and trailing spaces correctly.
Example Input & Output
Example 1
Input
"a "
Output
1
Explanation
Last word 'a' has 1
Example 2
Input
"hello"
Output
5
Explanation
Single word
Example 3
Input
""
Output
0
Explanation
Empty string
Example 4
Input
" fly me to the moon "
Output
4
Explanation
Last word 'moon' has 4
Example 5
Input
"Hello World"
Output
5
Explanation
Last word 'World' has 5 letters
Algorithm Flow

Recommendation Algorithm Flow for Length of Last Word
Solution Approach
Best Answers
java
class Solution {
public int solution(String s) {
s=s.trim();return s.length()-s.lastIndexOf(' ')-1;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
