Does This Shorthand Describe the Word?
StringsAuto-graded · 30 test casesLast updated
Check whether a shorthand of letters and skip counts exactly describes a word, handling multi-digit counts, leading zeros, overruns and leftover characters with a two-pointer scan.
Shorthand Check
You are given a lowercase string word and a shorthand string abbr. The shorthand is built from lowercase letters and decimal digits. Decide whether abbr is a valid shorthand for word.
The shorthand is read from left to right as a sequence of tokens:
- Letter token: a single lowercase letter. It must be identical to the next character of
wordthat has not yet been covered. - Number token: a maximal run of consecutive digits, read as one decimal integer
k. It covers the nextkcharacters ofword, whatever they are.
The shorthand is valid only if all of these hold:
- Every letter token matches the word character it lines up with.
- No number token begins with the digit
0. This rules out a skip of zero and numbers with padding such as03. A zero in a later position, as in10, is allowed. - No token runs past the end of the word. A number larger than the number of uncovered characters makes the shorthand invalid, and so does a letter token when the word is already fully covered.
- When the shorthand ends, every character of
wordhas been covered. Leftover word characters make it invalid. An emptyabbris therefore invalid for any nonempty word.
Digits that are next to each other always form a single number. For example, 12 means twelve, not one followed by two.
Return True if abbr is a valid shorthand for word, otherwise False.
Constraints
1 <= len(word) <= 1000000 <= len(abbr) <= 100000wordcontains only lowercase English letters.abbrcontains only lowercase English letters and digits.- Letter matching is exact and case-sensitive.
- Numbers in
abbrmay be very long, so avoid approaches that break on huge values. - Aim for
O(len(word) + len(abbr))time.
Examples
Example 1
Input: matches_abbreviation('internationalization', 'i18n')
Output: True
Example 2
Input: matches_abbreviation('substitution', 's10n')
Output: True
Example 3
Input: matches_abbreviation('apple', 'a3e')
Output: True
Example 4
Input: matches_abbreviation('apple', 'a03e')
Output: False
Example 5
Input: matches_abbreviation('word', '5')
Output: False
Hints
Hint 1
Use two pointers: one into the shorthand and one into the word marking the next uncovered character. Handle one token per step.
Hint 2
When you reach a digit, check right away whether it is '0'. Otherwise keep reading digits to build the number, and stop with False as soon as the value exceeds the number of uncovered word characters.
Hint 3
A letter token needs an uncovered character to exist and to be equal. After the shorthand is used up, the word pointer must sit exactly at the end of the word.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Scan the shorthand once from left to right, with a second pointer into the word that marks the first character not yet accounted for.
- Letter token: the word pointer must still be inside the word and the character there must equal the letter. If so, advance both pointers by one. Otherwise return
False. - Number token: if the first digit is
0, returnFalse. Otherwise keep reading digits, building the value asvalue * 10 + digit. After each digit, compare the value with the number of uncovered word characters. If it is larger, returnFalseimmediately. When the digits end, move the word pointer forward by the value.
After the shorthand is consumed, return True only if the word pointer equals len(word).
Why it is correct
The shorthand has exactly one tokenization: each letter is its own token and each maximal digit run is one number. No decisions are needed, so a single pass with no backtracking is enough.
The invariant is that after processing a prefix of the shorthand, that prefix describes exactly the first wi characters of the word.
- A letter step keeps the invariant because we verified the match before extending both prefixes.
- A number step keeps it because we verified that the skipped characters actually exist.
At the end, the whole shorthand describes word[:wi], which is the whole word exactly when wi == len(word). That final check also rejects partial coverage and an empty shorthand for a nonempty word.
Only the first digit of a number needs the zero test. A token starting with 0 is either a zero skip or a padded number, and both are invalid, while a later 0 as in 10 is fine.
Stopping as soon as the value exceeds the remaining length keeps the number bounded by about ten times the word length. This guards against overflow in fixed-width languages and avoids wasted work.
Complexity
- Time:
O(len(word) + len(abbr)). In fact onlyO(len(abbr))work is done, since the word pointer jumps over skipped characters. - Space:
O(1)auxiliary.
Reference solution
def matches_abbreviation(word: str, abbr: str) -> bool:
n = len(word)
m = len(abbr)
wi = 0 # next uncovered position in word
ai = 0 # current position in abbr
while ai < m:
ch = abbr[ai]
if '0' <= ch <= '9':
# A number token may not start with zero.
if ch == '0':
return False
skip = 0
while ai < m and '0' <= abbr[ai] <= '9':
skip = skip * 10 + (ord(abbr[ai]) - ord('0'))
# Once the skip exceeds what is left, it can only grow.
if skip > n - wi:
return False
ai += 1
wi += skip
else:
if wi >= n or word[wi] != ch:
return False
wi += 1
ai += 1
return wi == n