Check Whether a Letters-and-Numbers Abbreviation Matches a Word
MetaSoftware Engineer · Technical ScreenLast updated
Decide whether an abbreviation made of lowercase letters and decimal skip counts matches a given word, where each number skips that many characters and any number with a leading zero is invalid. It tests careful string scanning, multi-digit number parsing and end-of-input boundary checks.
A word can be abbreviated by replacing some of its non-empty substrings with their lengths, written in decimal. For example, "abbreviation" can be written as "a10n", "ab3v2t1on" or "12".
Given a string word and a string abbr, return whether abbr is a valid abbreviation of word.
Function Signature
def is_valid_abbreviation(word: str, abbr: str) -> bool:
Rules
- Read
abbrfrom left to right. A letter must equal the next unmatched character ofword. A maximal run of consecutive digits is read as one decimal numberk, and it skips the nextkcharacters ofword. - A digit run that starts with
0is invalid, so runs such as"0"or"05"never appear in a valid abbreviation. Every skip is therefore at least 1 character. abbris valid exactly when the end ofabbrand the end ofwordare reached at the same time. A skip that would go past the end ofwordmakesabbrinvalid, and so does reaching the end ofabbrwhile characters ofwordremain.- Letters are compared exactly.
Constraints
1 <= len(word) <= 10^5, andwordconsists of lowercase English letters.1 <= len(abbr) <= 10^5, andabbrconsists of lowercase English letters and the digits0to9.- Every maximal run of digits in
abbrhas at most 9 digits, so every skip count is below10^9and fits in a 32-bit signed integer.
Examples
Example 1
Input: word = "abbreviation", abbr = "ab3v2t1on"
Output: True
"ab" matches, 3 skips "bre", "v" matches, 2 skips "ia", "t" matches, 1 skips "i", and "on" matches. Both strings end together.
Example 2
Input: word = "substitution", abbr = "s010n"
Output: False
The digit run "010" starts with 0.
Example 3
Input: word = "apple", abbr = "a2e"
Output: False
After "a" matches and 2 skips "pp", the next character of word is "l", which does not equal "e".
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.