Notes

Personal notes on various topics

View on GitHub

Intuition

To find the length of the last word in a string, we can scan the string from the end, skipping any trailing spaces, and then count the characters until we hit another space or the start of the string.

Approach

Complexity

Code

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        n = len(s)

        ans = 0
        first_char = None
        for i in range(n - 1, -1, -1):
            c = s[i]
            if c == " " and first_char is not None:
                break
            elif c != " ":
                ans += 1
                first_char = first_char or c

        return ans

Back to Problem Statement