58. Length of Last Word
You receive a string s made up of English letters and space characters. A word is a maximal run of letters with no spaces inside it.
Write a function that receives s and returns the number of characters in the last word of the string — the rightmost run of letters. The string is guaranteed to contain at least one word, but it may begin or end with any amount of extra spaces, and words may be separated by more than one space.
For example, in " fly me to the moon " the last word is moon, so the answer is 4.
Example 1:
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World", which has 5 letters.
Example 2:
Input: s = " fly me to the moon "
Output: 4
Explanation: Trailing spaces are ignored; the last word is "moon" with 4 letters.
Example 3:
Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy", which has 6 letters.
Constraints:
- 1 ≤ s.length ≤ 10⁴
- s consists of English letters (upper and lower case) and spaces ' '
- s contains at least one word
Hints:
The last word is easiest to find from the right-hand end of the string.
Walk backwards: first skip any trailing spaces, then count letters until you hit a space or run out of string. That count is the answer, with no extra memory.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: s = "Hello World"
Expected output: 5