Problem Description
Given a string s consisting of words and spaces, return the length of the last word in the string. A word is defined as a maximal substring consisting of non-space characters.
Key Insights
- Remove any trailing spaces to handle edge cases.
- Find the last space in the string to isolate the last word.
- The length of the last word is the difference between the total string length (after trimming) and the position of the last space.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string (single pass to trim and another pass to count last word characters). Space Complexity: O(1), using constant extra space.
Solution
We first trim the string to remove trailing spaces which may cause incorrect identification of the last word. Then, we locate the last space character in the trimmed string. The length of the last word is calculated as the difference between the total string length and the index of the last space minus one. This approach uses basic string operations and requires constant space while processing the string in linear time.