Valid Word Abbreviation Problem
Description
LeetCode Problem 408.
A string can be abbreviated by replacing any number of non-adjacent, non-empty substrings with their lengths. The lengths should not have leading zeros.
For example, a string such as "substitution" could be abbreviated as (but not limited to):
"s10n"("s ubstitutio n")"sub4u4"("sub stit u tion")"12"("substitution")"su3i1u2on"("su bst i t u ti on")"substitution"(no substrings replaced)
The following are not valid abbreviations:
"s55n"("s ubsti tutio n", the replaced substrings are adjacent)"s010n"(has leading zeros)"s0ubstitution"(replaces an empty substring)
Given a string word and an abbreviation abbr, return whether the string matches the given abbreviation.
A substring is a contiguous non-empty sequence of characters within a string.
Example 1:
Input: word = "internationalization", abbr = "i12iz4n"
Output: true
Explanation: The word "internationalization" can be abbreviated as "i12iz4n" ("i nternational iz atio n").
Example 2:
Input: word = "apple", abbr = "a2e"
Output: false
Explanation: The word "apple" cannot be abbreviated as "a2e".
Constraints:
1 <= word.length <= 20wordconsists of only lowercase English letters.1 <= abbr.length <= 10abbrconsists of lowercase English letters and digits.- All the integers in
abbrwill fit in a 32-bit integer.
Solution
Approach: Two Pointers
There is no need to expand the abbreviation. Walk through word with an index i and through abbr with an index j, and keep skip, the number currently being read from abbr:
- If
abbr[j]is a digit, it extendsskip:skip = skip * 10 + digit. A'0'whileskipis still0means the number starts with a zero ("s010n") or is just"0"("s0ubstitution"). Both are invalid, so returnfalse. - If
abbr[j]is a letter, first jump over the letters the number stands for:i += skip, then resetskipto0. Nowword[i]must exist and equalabbr[j]; if it does, moveipast it.
The loop stops when either string runs out. The abbreviation matches only if both are used up exactly: j == n and i + skip == m. Adding skip here handles an abbreviation that ends in a number ("i12iz4n" ends with a letter, but "sub4u4" ends with 4, which is still pending when the loop ends).
Watch the size of the numbers: abbr can hold 2147483647, and i + skip then overflows a 32-bit int. The Java and C++ versions keep skip in a 64-bit integer.
Complexity: O(m + n) time, where m and n are the lengths of word and abbr. O(1) extra space.
class Solution:
def validWordAbbreviation(self, word: str, abbr: str) -> bool:
m, n = len(word), len(abbr)
i = j = 0
skip = 0 # the number being read from abbr
while i < m and j < n:
c = abbr[j]
if c.isdigit():
if c == "0" and skip == 0: # a leading zero, or a bare "0"
return False
skip = skip * 10 + int(c)
else:
i += skip # jump over the letters the number stands for
skip = 0
if i >= m or word[i] != c:
return False
i += 1
j += 1
return i + skip == m and j == n