Valid Word Abbreviation
Easy
Topics
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
true.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
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
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
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
- Keep an index into
sand an index intot, both at 0. - If the current character of
tis a letter, it must equal the current character ofs. Advance both by one. - 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 thesindex by it. - Reject if the
sindex 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 trueComplexity
- 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
trueas 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)import java.util.*;
class Solution {
public boolean validWordAbbreviation(String s, String t) {
int i = 0, j = 0;
while (i < s.length() && j < t.length()) {
char c = t.charAt(j);
if (c >= '0' && c <= '9') {
if (c == '0') return false;
long num = 0;
while (j < t.length() && t.charAt(j) >= '0' && t.charAt(j) <= '9') {
num = num * 10 + (t.charAt(j) - '0');
j++;
}
i += (int) Math.min(num, (long) s.length() + 1);
} else {
if (s.charAt(i) != c) return false;
i++;
j++;
}
}
return i == s.length() && j == t.length();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool validWordAbbreviation(string s, string t) {
size_t i = 0, j = 0;
while (i < s.size() && j < t.size()) {
if (isdigit((unsigned char)t[j])) {
if (t[j] == '0') return false;
long long num = 0;
while (j < t.size() && isdigit((unsigned char)t[j])) {
num = num * 10 + (t[j] - '0');
j++;
}
i += (size_t)num;
} else {
if (s[i] != t[j]) return false;
i++;
j++;
}
}
return i == s.size() && j == t.size();
}
};/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/ var validWordAbbreviation = function(s, t) {
const isDigit = (c) => c >= '0' && c <= '9';
let i = 0, j = 0;
while (i < s.length && j < t.length) {
if (isDigit(t[j])) {
if (t[j] === '0') return false;
let num = 0;
while (j < t.length && isDigit(t[j])) {
num = num * 10 + (t.charCodeAt(j) - 48);
j++;
}
i += num;
} else {
if (s[i] !== t[j]) return false;
i++;
j++;
}
}
return i === s.length && j === t.length;
};