Return the length of the last word in a string, ignoring trailing spaces.
Problem
Given a string s consisting of words separated by spaces, determine the length of the last word.
A word is a maximal substring made up of non-space characters. The input may contain leading spaces, trailing spaces, or multiple spaces between words.
Your task is to scan the string and return the number of characters in the final word.
Notes
- A word is defined as a contiguous sequence of non-space characters.
- Ignore any spaces at the end of the string.
- If the string contains no word at all, return
0.
Input Format
- A single string
s. - The string may contain spaces and non-space characters.
Output Format
- Return one integer: the length of the last word in
s.
Constraints
smay contain leading/trailing/multiple spaces.- The string may be empty.
Example 1
Input
s = "Hello World"
Output
5
Explanation
The last word is "World", which has length 5.
Example 2
Input
s = " fly me to the moon "
Output
4
Explanation
After ignoring trailing spaces, the last word is "moon".
Show 1 more example
Example 3
Input
s = " "
Output
0
Explanation
There is no word in the string.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.