A string can be shortened by replacing any number of non-adjacent, non-empty substrings with their lengths (without leading zeros).
For example, the string "implementation" can be abbreviated in several ways, such as:
Invalid abbreviations include:
You are given a string named word and an abbreviation named abbr, return true if abbr correctly abbreviates word, otherwise return false.
A substring is a contiguous non-empty sequence of characters within a string.
Example 1:
Input: word = "apple", abbr = "a3e"
Output: trueExample 2:
Input: word = "international", abbr = "i9l"
Output: falseExample 3:
Input: word = "abbreviation", abbr = "abbreviation"
Output: trueConstraints:
1 <= word.length <= 100word is made up of only lowercase English letters.1 <= abbr.length <= 100abbr is made up of lowercase English letters and digits.abbr fit in a 32-bit integer.class Solution:
def validWordAbbreviation(self, word: str, abbr: str) -> bool:
n, m = len(word), len(abbr)
i = j = 0
while i < n and j < m:
if abbr[j] == '0':
return False
if word[i] == abbr[j]:
i, j = i + 1, j + 1
elif abbr[j].isalpha():
return False
else:
subLen = 0
while j < m and abbr[j].isdigit():
subLen = subLen * 10 + int(abbr[j])
j += 1
i += subLen
return i == n and j == mWhere and are the lengths of the strings and , respectively.