[LeetCode] 408. Valid Word Abbreviation_Easy

Given a non-empty string s and an abbreviation abbr, return whether the string matches with the given abbreviation.

A string such as "word" contains only the following valid abbreviations:

["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]

Notice that only the above abbreviations are valid abbreviations of the string "word". Any other string is not a valid abbreviation of "word".

Note:
Assume s contains only lowercase letters and abbr contains only lowercase letters and digits.

Example 1:

Given s = "internationalization", abbr = "i12iz4n":

Return true.

Example 2:

Given s = "apple", abbr = "a2e":

Return false.

思路就是依次将abbr的数字弄出来, 然后再word上面相加, 否则就比较char, 最后出来loop之后应该是都指到各自的length上面.

Code

class Solution:
    def validWordAbbreviation(self, word, abbr):
       nums, lw, la, pw, pa = "0123456789", len(word), len(abbr),0,0
        while pw < lw and pa < la:
            num = ""
            while abbr[pa] in nums:
                num += abbr[pa]
                if num[0] == '0': return False
                pa += 1
                if pa == la:
                    return len(word[pw:]) == int(num)
            if not num:
                if word[pw] != abbr[pa]:
                    return False
                else:
                    pw += 1
                    pa += 1
            else:
                pw += int(num)
        return pw == lw and pa == la
            
        

猜你喜欢

转载自www.cnblogs.com/Johnsonxiong/p/9503716.html
今日推荐