Valid Word Abbreviation

Easy

Topics
Two PointersString

A string can be abbreviated by replacing any number of non-adjacent, non-empty substrings with their lengths. For example "substitution" can be abbreviated as "s10n" or "sub4u4", but not as "s55n" (the two replaced substrings would be adjacent) nor "s010n" (a length with a leading zero).

Given a string s and an abbreviation t, return true if t is a valid abbreviation of s.

The two strings here are named s and t because that is what the judge calls them; on LeetCode they are word and abbr.

Example 1

wordi0n1t2e3r4n5a6t7i8o9n10a11l12i13z14a15t16i17o18n19
abbri12iz4n
kept, must matchcovered by a count
The abbreviation is read as instructions over the word: a letter must match the character under it, a number covers that many characters. Reading it as "i", then 12 skipped, then "i", then "z", then 4 skipped, then "n" lands exactly on the end of a 20-character word with the abbreviation fully used, so the answer is true.
One cell per character; the small numbers under the word are indices.
Input:  s = "internationalization", t = "i12iz4n"
Output: true
Explanation: i, then 12 characters skipped, then iz, then 4 skipped, then n — and that lands exactly on the end.

Example 2

worda0p1p2l3e4
abbra2e
kept, must matchcovered by a countwhere it breaks
It breaks at index 3 of the word, where l is expected to be e, so the answer is false.
Input:  s = "apple", t = "a2e"
Output: false
Explanation: After a and two skipped characters the next letter of s is l, not e.

Example 3

worda0p1p2l3e4
abbra3e
kept, must matchcovered by a count
Reading it as "a", then 3 skipped, then "e" lands exactly on the end of a 5-character word with the abbreviation fully used, so the answer is true.
Input:  s = "apple", t = "a3e"
Output: true
Explanation: a, then ppl skipped, then e — three characters is the right count, where two was not.

Example 4

worda0
abbr01
A count here starts with 0, which is never allowed — a zero-length stretch is how two counts side by side would be spelled. The answer is false.
Input:  s = "a", t = "01"
Output: false
Explanation: A leading zero is never allowed in a length.

Constraints

  • 1 <= s.length <= 20
  • s consists of only lowercase English letters
  • 1 <= t.length <= 10
  • t consists of only lowercase English letters and digits
Editorial — intuition, approach, complexity and pitfalls

Intuition

An abbreviation is a set of instructions for walking the original string: a letter means "the next character must be this", and a number means "skip this many". So verification is a single simultaneous walk of both strings with two independent cursors.

The two cursors advance at different rates, which is the whole content of the problem. The abbreviation cursor moves one character per letter but several per number, while the word cursor jumps by the number’s value.

The invalid forms both come from the number parsing rather than the matching. A leading zero is banned outright, and so is a run that would have come from two adjacent replacements — which is precisely why a 0 must never be accepted as a length: a zero-length replacement is how two adjacent ones would be spelled.

Approach

  1. Keep an index into s and an index into t, both at 0.
  2. If the current character of t is a letter, it must equal the current character of s. Advance both by one.
  3. If it is a digit, reject immediately when that digit is 0, since no valid length starts with zero. Otherwise read the whole run of digits as one number and advance the s index by it.
  4. Reject if the s index ever runs past the end. Accept only when both indices land exactly on the end at the same time.

Walkthrough

s = "internationalization"   (20 characters)
t = "i12iz4n"

 t      s index    action
 "i"       0       matches s[0]=i, both advance -> s index 1
 "12"      1       skip 12                     -> s index 13
 "i"      13       matches s[13]=i             -> s index 14
 "z"      14       matches s[14]=z             -> s index 15
 "4"      15       skip 4                      -> s index 19
 "n"      19       matches s[19]=n             -> s index 20

t exhausted and s index is 20, the length of s
answer true

Complexity

  • Time — O(n): each character of both strings is examined at most once.
  • Space — O(1): two indices and one accumulator.

Common Pitfalls

  • Accepting a leading zero. "01" and "s010n" must both be rejected, and a parser that reads digits greedily without checking the first one will happily accept them.
  • Returning true as soon as the abbreviation is exhausted. Both strings must finish together — an abbreviation that covers only a prefix of the word is not an abbreviation of it.
  • Letting the word index run past the end silently. In a language that clamps or wraps an out-of-range slice, a number far too large can look like a match.
  • Reading a multi-digit number one digit at a time. "i12iz4n" skips twelve characters, not one then two.

Full Solution — all languages

class Solution:
    def validWordAbbreviation(self, s, t):
        i = j = 0
        while i < len(s) and j < len(t):
            if t[j].isdigit():
                if t[j] == '0':
                    return False
                num = 0
                while j < len(t) and t[j].isdigit():
                    num = num * 10 + int(t[j])
                    j += 1
                i += num
            else:
                if s[i] != t[j]:
                    return False
                i += 1
                j += 1
        return i == len(s) and j == len(t)
SensAI
Beta
Tap the mic to stop voice mode