my python solution beats around 91%, O(min(len(abbr), len(word))


  • 0
    I
    class Solution(object):
        def validWordAbbreviation(self, word, abbr):
            """
            :type word: str
            :type abbr: str
            :rtype: bool
            """
            if not abbr:
                return False
            
            word_idx = 0
            abbr_idx = 0
            curr_num = 0
            
            while word_idx < len(word) and abbr_idx < len(abbr):
                if not abbr[abbr_idx].isdigit():
                    if word[word_idx] == abbr[abbr_idx]:
                        word_idx += 1
                        abbr_idx += 1
                    else:
                        return False
                        
                else:
                    if abbr[abbr_idx] == "0":
                        return False
                    
                    while abbr_idx < len(abbr) and abbr[abbr_idx].isdigit():
                        curr_num *= 10
                        curr_num += int(abbr[abbr_idx])
                        abbr_idx += 1
                        
                    if len(word) - word_idx < curr_num:
                        return False
                    else:
                        word_idx += curr_num
                    
                    curr_num = 0
    
            return word_idx == len(word) and abbr_idx == len(abbr)

Log in to reply
 

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