Valid Word Abbreviation

Here’s a code snippet to check if a given abbreviation abbr is valid for a particular word word:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def validWordAbbreviation(self, word: str, abbr: str) -> bool:
        i = 0
        j = 0
        while i < len(word) and j < len(abbr):
            if abbr[j].isalpha():
                if word[i] != abbr[j]:
                    return False
                i += 1
                j += 1
            else:
                if abbr[j] == '0':
                    return False
                num = 0
                while j < len(abbr) and abbr[j].isdigit():
                    num = num * 10 + int(abbr[j])
                    j += 1
                i += num
        return i == len(word) and j == len(abbr)

Explanation

  • We iterate through both the word and abbreviation using indices i and j.
  • If the current character in abbr is a letter, we check if it matches the corresponding character in word. If not, we return False.
  • If the current character in abbr is a digit, we collect the subsequent digits to form a number, but we make sure the number doesn’t start with 0.
  • We skip the corresponding number of characters in word as indicated by the collected number.
  • Finally, we check if both i and j reached the end of the word and abbr respectively, returning True if they have, and False otherwise.