DSA problem
Length of Last Word
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 consisting of non-space characters only. The string may contain leading, trailing, or multiple consecutive spaces, so you cannot assume the last character is part of a word.
For example, in the string " fly me to the moon " the last word is "moon", whose length is 4. It is guaranteed that there is at least one word in s.
Examples
Example 1
Input:
s = "Hello World"Output:
5Explanation: The last word is "World", which has 5 characters.
Example 2
Input:
s = " fly me to the moon "Output:
4Explanation: Trailing spaces are ignored. The last word is "moon", which has 4 characters.
Example 3
Input:
s = "luffy is still joyboy"Output:
6Explanation: The last word is "joyboy", which has 6 characters.
Constraints
- 1 <= s.length <= 10^4
- s consists of only English letters and spaces ' '.
- There will be at least one word in s.
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.