Problem Statement in English
You’re given a string s consisting of words and spaces. A word is defined as a maximal substring consisting of non-space characters only. Your task is to return the length of the last word in the string. If the last word does not exist, return 0.
Approach
We can just strip the string to remove any leading or trailing spaces, then split it by spaces and return the length of the last word. If there are no words, we return 0.
To do it in $O(1)$ space, we can iterate from the end of the string to find the last word without creating a new list.
And we’re done!
Solution in Python
class Solution:
def lengthOfLastWord(self, s: str) -> int:
return len(s.strip().split(" ")[-1])
Complexity
Time: $O(n)$
Since we are iterating through the stringsonce to strip and split it, the time complexity is linear with respect to the length of the string.Space: $O(n)$
Since we are creating a new list when we split the string, the space complexity is linear with respect to the length of the string. But we can optimize it to $O(1)$ if we just iterate from the end of the string to find the last word without creating a new list. I was just lazy to do that. This was just too tempting to pass.
And we are done.