Easy to understand Python solution

  • 0

    I split abbr with re and iterate over them. I move to the next position when the token is a number except '0' (or any number string begins with '0'), or check whether the character in abbr is the same as where I am in word. In the end I check if I go through all the items in abbr and I am exactly the end of word.

    class Solution(object):
        def validWordAbbreviation(self, word, abbr):
            :type word: str
            :type abbr: str
            :rtype: bool
            tokens = [t for t in re.split('(\D)', abbr) if t]
            cur = 0
            while tokens:
                t = tokens.pop(0)
                if t.isdigit():
                    if t[0] == '0':
                        return False
                    cur += int(t)
                    if t != word[cur]:
                        return False
                    cur += 1
                if cur >= len(word):
            return cur == len(word) and not tokens

Log in to reply

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