LC.408. Valid Word Abbreviation

LC.408. Valid Word Abbreviation_第1张图片

class Solution(object):
    def validWordAbbreviation(self, word, abbr):
        """
        index 指示word
        stack 存abbr的数字,这样更方便,当然也可以不用stack
        """
        word, abbr = word + 'a', abbr + 'a'
        index = 0
        stack = []
        for char in abbr:

            if char.isalpha():
                if len(stack):
                    step = int(''.join(map(str, stack)))
                    if len(str(step)) != len(stack) or step == 0:
                        return False
                    index += step
                if index >= len(word):
                    return False
                if word[index] != char:
                    return False
                stack = []
                index += 1
            else:
                stack.append(char)
        return index == len(word)

你可能感兴趣的:(LeetCode)