Python solution accepted


  • 0
    A

    If abbr is longer than the word, it's not valid. There can be numbers like 10, but if it's 02, then it's invalid as one of the letters is collapsing to a 0. 2 is valid, 02 is not.

    If char is a-z, then check if it's same as the marker. If it's not, then collect all digits before combining them to be an int. Code below, hope it helps!

        def validWordAbbreviation(self, word, abbr):
            """
            :type word: str
            :type abbr: str
            :rtype: bool
            """
            
            if len(abbr) > len(word):
                return False
            marker = 0
            digits = []
            for char in abbr:
                if char.isalpha():
                    if digits:
                        num = int(''.join(digits))
                        marker = marker + num
                        digits = []
                    if marker >= len(word): # otherwise, can get OoB exception
                        return False
                    elif char != word[marker]:
                        return False
                    else:
                        marker = marker + 1
                else:
                    if char == '0' and not digits: # to handle leading zeroes
                        return False
                    digits.append(char)
            if digits:
                num = int(''.join(digits)) # what if the abbr is just a number
                marker = marker + num
            if marker != len(word):
                return False
            return True

Log in to reply
 

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