58. Length of Last Word ๐
Last updated
Was this helpful?
Last updated
Was this helpful?
Difficulty: Easy
- Tags: String
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 only.
Example 1:
Input:
Output:
Explanation: The last word is "World" which has a length of 5.
Example 2:
Input:
Output:
Explanation: The last word is "moon" with a length of 4.
Example 3:
Input:
Output:
Explanation: The last word is "joyboy" which has a length of 6.
The input string s
consists of only printable ASCII characters.
The string may contain leading or trailing spaces, but it will not contain multiple consecutive spaces.
To solve this problem, we trim the string to remove any leading or trailing spaces, then count the characters of the last word by iterating from the end of the string until we encounter a space.
O(n): The time complexity is linear, where n
is the length of the trimmed input string.
O(1): The space complexity is constant as we only use a few variables.
You can find the full solution .