Length of Last Word

Problem Id: 58 Difficulty: Easy Tag: String


Intuition

Use one pointer from end to the start of last word.

Solution


import string


class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        start_word = False
        count = 0
        for c in s[::-1]:
            if not start_word:
                if c == ' ':
                    continue
                start_word = True
                count += 1
            else:
                if c in string.ascii_letters:
                    count += 1
                else:
                    break
        return count