Length of Last Word
Easy · Strings · String
Problem
You are given a string s made of English letters and spaces. A word is a maximal run of letters with no space inside it.
Return the length of the last word in s.
The string may start or end with any number of spaces, and words may be separated by more than one space, so the last character is not always part of the last word. s always contains at least one word.
Examples
Input: s = "Hello World" Output: 5
The last word is "World".
Input: s = " fly me to the moon " Output: 4
The trailing spaces are skipped; the last word is "moon".
Input: s = "luffy is still joyboy" Output: 6
The last word is "joyboy".
Constraints
- 1 <= len(s) <= 10^4
- s holds only English letters and spaces
- s contains at least one word
Approaches
- Split into words — time O(n), space O(n)
Follow-up
The scan never needs more than the tail of the string. Could you answer for the k-th word from the end, or for a string arriving as a stream where you only see each character once?
Related problems
Start free on Cariara · Coding problems · System design studio