Length of Last Word
The key idea
The last word lives at the right end. Scan from the right: first skip any trailing spaces, then count letters until you hit a space or run off the front. No need to find every word.
Problem
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 of non-space characters.
Constraints
1 <= s.length <= 10^4sconsists of only English letters and spaces' '.- There will be at least one word in
s.
Examples
Input: s = "Hello World"
Output: 5
Input: s = " fly me to the moon "
Output: 4
Input: s = "luffy is still joyboy"
Output: 6
Complexity
Time: O(n) Space: O(1)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization