Short Python Solution - 42ms


  • 2
    F
    class Solution(object):
        def validWordAbbreviation(self, word, abbr):
            """
            :type word: str
            :type abbr: str
            :rtype: bool
            """
            i, n = 0, ''
            for c in abbr:
                if c.isalpha():
                    i += int('0'+n)
                    if i >= len(word) or c != word[i]: return False
                    i, n = i+1, ''
                else:
                    if n == '' and c == '0': return False
                    n += c
            return i+int('0'+n) == len(word)
    

  • 0
    F

    nice neat code!
    a little bit update based on your code:

    class Solution(object):
        def validWordAbbreviation(self, word, abbr):
            """
            :type word: str
            :type abbr: str
            :rtype: bool
            """
            i, n = 0, "0"
            for c in abbr:
                if c.isdigit():
                    if n == c:
                        return False
                    n += c
                else:
                    i += int(n)
                    if i>=len(word) or word[i] != c:
                        return False
                    i += 1
                    n = '0'
                    
            return i+int(n)== len(word)
    
    

  • 0

    @flyerx

    should the n == c check be n == c == '0' ?


Log in to reply
 

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