KatInterview

Does This Shorthand Describe the Word?

StringsAuto-graded · 30 test cases
MediumAuto-gradedStringstwo-pointersstring-parsingsimulation

Last 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 word that has not yet been covered.
  • Number token: a maximal run of consecutive digits, read as one decimal integer k. It covers the next k characters of word, whatever they are.

The shorthand is valid only if all of these hold:

  1. Every letter token matches the word character it lines up with.
  2. No number token begins with the digit 0. This rules out a skip of zero and numbers with padding such as 03. A zero in a later position, as in 10, is allowed.
  3. 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.
  4. When the shorthand ends, every character of word has been covered. Leftover word characters make it invalid. An empty abbr is 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) <= 100000
  • 0 <= len(abbr) <= 100000
  • word contains only lowercase English letters.
  • abbr contains only lowercase English letters and digits.
  • Letter matching is exact and case-sensitive.
  • Numbers in abbr may 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.