Length of the Last Word
Given a string s consisting of words and spaces, your task is to find the length of the last word in the string. A "word" is defined as a maximal substring consisting of non-space characters only. This is a common string manipulation task encountered in various programming scenarios, from text processing to command-line interfaces.
Problem Description
Your goal is to write a function that takes a string s as input and returns an integer representing the length of the last word.
Key Requirements:
- Identify words within the string, where words are separated by one or more spaces.
- Determine the "last" word, which is the word that appears furthest to the right in the string.
- Return the number of characters in that last word.
Expected Behavior:
- The function should correctly handle strings with leading spaces, trailing spaces, and multiple spaces between words.
- If the string contains only spaces or is empty, the length of the last word should be considered 0.
Edge Cases to Consider:
- An empty input string.
- A string containing only spaces.
- A string with trailing spaces.
- A string with leading spaces.
- A string with multiple spaces between words.
- A string with a single word.
Examples
Example 1:
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World", which has a length of 5.
Example 2:
Input: s = " fly me to the moon "
Output: 4
Explanation: The last word is "moon", which has a length of 4.
Example 3:
Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy", which has a length of 6.
Example 4:
Input: s = "a"
Output: 1
Explanation: The last word is "a", which has a length of 1.
Example 5:
Input: s = " "
Output: 0
Explanation: The string contains only spaces, so the length of the last word is 0.
Constraints
- 1 <= s.length <= 10^4
- s consists of only English letters and spaces ' '.
- There will be at least one word in
sifsis not empty and does not consist solely of spaces.
Notes
- Consider how you can efficiently process the string to find the last word.
- Think about how to handle whitespace at the beginning and end of the string.
- The problem statement guarantees that if the string is not empty and not all spaces, there will be at least one word. This simplifies some edge case handling.