You are 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.
Note: A substring is a contiguous non-empty sequence of characters within a string.
Example 1:
Input: s = "Hello World"
Output: 5Explanation: The last word is "World" with length 5.
Example 2:
Input: s = " fly me to the moon "
Output: 4Explanation: The last word is "moon" with length 4.
Example 3:
Input: s = "luffy is still joyboy"
Output: 6Explanation: The last word is "joyboy" with length 6.
Constraints:
1 <= s.length <= 10,000s consists of only English letters and spaces ' '.s.Before attempting this problem, you should be comfortable with:
We need to find the length of the last word, where words are separated by spaces. Trailing spaces complicate matters since the last word might not be at the very end of the string. By scanning forward, we track the current word's length and reset it when we encounter a new word after spaces.
length to 0 and start at index 0.length.length to 0 (we're starting a new word).length.length after the loop completes.Scanning from the end is more direct since we only care about the last word. First skip any trailing spaces, then count characters until we hit a space or the beginning of the string. This avoids processing earlier parts of the string entirely.
length until a space is found or we reach the start.length.Most languages provide string manipulation functions that handle splitting and trimming. By splitting the string on spaces and taking the last non-empty segment, we get the last word directly. This trades some efficiency for code simplicity and readability.
Strings like "Hello World " have trailing spaces after the last word. If you simply scan from the end without first skipping spaces, you will count zero characters. Always skip trailing spaces before counting the last word's length.
The input can have multiple consecutive spaces between words or at the beginning and end. Code that assumes exactly one space between words may produce incorrect results or fail on edge cases like " fly me to the moon ".