58. Length of Last Word ๐
Difficulty: Easy
- Tags: String
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 only.
Examples
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.
Constraints
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.
Solution ๐ก
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.
Java
Time Complexity โณ
O(n): The time complexity is linear, where
n
is the length of the trimmed input string.
Space Complexity ๐พ
O(1): The space complexity is constant as we only use a few variables.
You can find the full solution here.
Last updated