AAlgoLoopSpaced repetition for LeetCode
EASYStringLeetCode ↗

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

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

410310
Step-by-step visualization
Start free →

More String problems