408. Valid Word Abbreviation - Explanation
Description
A string can be shortened by replacing any number of non-adjacent, non-empty substrings with their lengths (without leading zeros).
For example, the string "implementation" can be abbreviated in several ways, such as:
- "i12n" -> ("i mplementatio n")
- "imp4n5n" -> ("imp leme n tatio n")
- "14" -> ("implementation")
- "implemetation" -> (no substrings replaced)
Invalid abbreviations include:
- "i57n" -> (i mplem entatio n, adjacent substrings are replaced.)
- "i012n" -> (has leading zeros)
- "i0mplementation" (replaces an empty substring)
You are given a string named word and an abbreviation named abbr, return true if abbr correctly abbreviates word, otherwise return false.
A substring is a contiguous non-empty sequence of characters within a string.
Example 1:
Input: word = "apple", abbr = "a3e"
Output: trueExample 2:
Input: word = "international", abbr = "i9l"
Output: falseExample 3:
Input: word = "abbreviation", abbr = "abbreviation"
Output: trueConstraints:
1 <= word.length <= 100wordis made up of only lowercase English letters.1 <= abbr.length <= 100abbris made up of lowercase English letters and digits.- All digit-only substrings of
abbrfit in a32-bit integer.
Topics
Prerequisites
Before attempting this problem, you should be comfortable with:
- Two Pointers Technique - Simultaneously traversing two strings with independent indices
- String Parsing - Converting sequences of digit characters into numeric values
- Character Classification - Distinguishing between alphabetic characters and digits
1. Two Pointers
Intuition
We need to verify that the abbreviation correctly represents the word. The abbreviation contains letters and numbers, where numbers indicate how many characters to skip. We use two pointers to traverse both strings simultaneously. When we see a letter in the abbreviation, it must match the current character in the word. When we see a number, we parse the full number and skip that many characters in the word. A leading zero in any number makes the abbreviation invalid.
Algorithm
- Initialize two pointers:
ifor the word andjfor the abbreviation. - While both pointers are within bounds:
- If
abbr[j]is'0', returnfalse(leading zeros are invalid). - If
abbr[j]is a letter:- Check if
word[i] == abbr[j]. If not, returnfalse. - Increment both
iandj.
- Check if
- If
abbr[j]is a digit:- Parse the complete number by collecting consecutive digits.
- Advance
iby that number (skip characters in the word).
- If
- Return
trueif both pointers have reached the end of their respective strings.
class Solution:
def validWordAbbreviation(self, word: str, abbr: str) -> bool:
n, m = len(word), len(abbr)
i = j = 0
while i < n and j < m:
if abbr[j] == '0':
return False
if word[i] == abbr[j]:
i, j = i + 1, j + 1
elif abbr[j].isalpha():
return False
else:
subLen = 0
while j < m and abbr[j].isdigit():
subLen = subLen * 10 + int(abbr[j])
j += 1
i += subLen
return i == n and j == mTime & Space Complexity
- Time complexity:
- Space complexity:
Where and are the lengths of the strings and , respectively.
Common Pitfalls
Allowing Leading Zeros in Numbers
The abbreviation "a02b" is invalid because the number has a leading zero. Many solutions forget to check for this edge case. Before parsing a multi-digit number, always verify that the first digit is not '0'. A leading zero makes the abbreviation invalid regardless of the number's value.
Skipping Past the End of the Word
After parsing a number from the abbreviation and advancing the word pointer, you must verify that the pointer does not exceed the word length. For example, with word = "hi" and abbr = "5", skipping 5 characters goes beyond the word's length. Always check i <= n after advancing, and ensure both pointers reach their respective ends simultaneously.
Sign in to join the discussion