Skip trailing spaces, then count
Walk from the right. Ignore trailing spaces, then count until the next space or the start.
The last word is the last run of non-space characters. Starting from the end means you never look at the earlier words.
Algorithm
- Skip trailing spaces.
- Count the next run of letters.
- Return the count.
- Time
- O(n)
- Space
- O(1)
class Solution: def lengthOfLastWord(self, s: str) -> int: i = len(s) - 1 while i >= 0 and s[i] == " ": i -= 1 n = 0 while i >= 0 and s[i] != " ": n += 1 i -= 1 return n