8-line one-pass Python solution

  • 0
    def lengthOfLastWord(self, s):
        letter_found, letter_start = False, -1
        for i, ch in enumerate(reversed(s)):
            if ch != ' ': 
                if not letter_found: letter_start = i
                letter_found = True
                if letter_found: return i - letter_start
        return len(s) - letter_start if letter_found else 0

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.