Valid Word Abbreviation

Check if a word matches an abbreviation that interleaves letters with digit counts. Two pointers, no leading zeros.

Easy
Time O(n) Space O(1)
LeetCode
5 min read
two-pointers string

Problem#

Given a string word and an abbreviation abbr (letters interleaved with non-negative integer “skip counts”), return true if the abbreviation correctly describes the word. Leading zeros in any number are invalid ("01" is not a legal skip).

Examples#

  • word = "internationalization", abbr = "i12iz4n"true (i + skip 12 + iz + skip 4 + n)
  • word = "apple", abbr = "a2e"false (skip of 2 lands on l, not e)
  • word = "a", abbr = "01"false (leading zero)

Constraints#

  • 1 <= word.length <= 20, lowercase letters.
  • 1 <= abbr.length <= 10, lowercase letters and digits.

Hints#

Hint 1
Walk both strings with two indices; when you hit a digit, consume the whole number before jumping.
Hint 2
Reject any number that starts with '0' immediately — no need to parse further.

Approach#

Regex / split — readable but pays allocation cost and hides the leading-zero edge case.
Two pointersi over word, j over abbr. When abbr[j] is a digit, accumulate the number and advance i by it. Linear, no allocations.

Solution#

Valid Word Abbreviation
class Solution {
public:
bool validWordAbbreviation(string word, string abbr) {
int i = 0, j = 0;
const int n = word.size(), m = abbr.size();
while (i < n && j < m) {
if (isdigit(abbr[j])) {
if (abbr[j] == '0') return false; // leading zero
int num = 0;
while (j < m && isdigit(abbr[j])) {
num = num * 10 + (abbr[j] - '0');
++j;
}
i += num;
} else {
if (word[i] != abbr[j]) return false;
++i; ++j;
}
}
return i == n && j == m;
}
};

Editorial#

The two pointers play different roles: j walks abbr token-by-token (either a single letter or an entire digit run), and i jumps over word by exactly the skip distance. Treating the digit run atomically is what makes the algorithm linear — we never re-scan characters. The leading-zero check is a one-liner because a legal number ≥ 1 cannot start with '0', and '0' itself is illegal too (skipping zero characters is meaningless and explicitly disallowed). The final equality check (i == n && j == m) catches the case where one string is exhausted before the other.

Complexity#

  • Time: O(n + m) — single pass over each string.
  • Space: O(1) — just the two indices and the running number.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.