Length of Last Word - Problem
Given a string s consisting of words and spaces, return the length of the last word in the string.
A word is defined as a maximal substring consisting of non-space characters only. This means spaces act as delimiters between words, and you need to find the final word before any trailing spaces.
Example: In the string "Hello World", the last word is "World" with length 5.
Note: The input string may contain leading and/or trailing spaces, but you should focus only on the actual words separated by spaces.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "Hello World"
โบ
Output:
5
๐ก Note:
The last word is "World" which has 5 characters.
example_2.py โ Trailing Spaces
$
Input:
s = " fly me to the moon "
โบ
Output:
4
๐ก Note:
The last word is "moon" (length 4). The trailing spaces are ignored.
example_3.py โ Single Word
$
Input:
s = "luffy"
โบ
Output:
5
๐ก Note:
There is only one word "luffy" in the string, so it's also the last word with length 5.
Constraints
- 1 โค s.length โค 104
- s consists of only English letters and spaces ' '
- The string contains at least one word
Visualization
Tap to expand
Understanding the Visualization
1
Start from the Right
Begin at the end of the string, like starting from the right side of a book spine
2
Skip Extra Spaces
Move left past any trailing spaces, like ignoring empty space on the spine
3
Count the Last Word
Count each character of the last word until you hit a space
4
Return the Count
You now have the length of the last word without reading the entire spine
Key Takeaway
๐ฏ Key Insight: Starting from the end eliminates unnecessary processing and naturally handles edge cases like trailing spaces
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code