Non-regex Python solution


  • 1
    N
    class Solution(object):
        def validWordAbbreviation(self, word, abbr):
            """
            :type word: str
            :type abbr: str
            :rtype: bool
            """
            if not word or not abbr:
                return
    
            digits = [str(i) for i in xrange(10)]
            i = 0
            j = 0
            while i < len(word) and j < len(abbr):
                if word[i] == abbr[j]:
                    i += 1
                    j += 1
                    continue
                
                if abbr[j] not in digits[1:]:
                    return False
                
                digits_start = j
                while j < len(abbr) and abbr[j] in digits:
                    j += 1
                
                i += int(abbr[digits_start:j])
    
            return i == len(word) and j == len(abbr)
    

  • 0
    W

    @natalia6 Nice solution! One minor suggestion: you do not need to define the list digits; instead, you can use ch.isdigit() to determine if the character ch is a digit or not.


  • 0

    @WKVictor Yes, but there is a little problem for this case. 0 in abbr is not allowed and will return False. However ch.isdigit() will return True. You can use 'not abbr[j].isdigit() or abbr[j] == '0'' instead of ' abbr[j] not in digits[1:]' .


Log in to reply
 

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