Generalized Abbreviation Problem
Description
LeetCode Problem 320.
A word's generalized abbreviation can be constructed by taking any number of non-overlapping and non-adjacent substrings and replacing them with their respective lengths.
- For example,
"abcde"can be abbreviated into:"a3e"("bcd"turned into"3")"1bcd1"("a"and"e"both turned into"1")"5"("abcde"turned into"5")"abcde"(no substrings replaced)
- However, these abbreviations are invalid:
"23"("ab"turned into"2"and"cde"turned into"3") is invalid as the substrings chosen are adjacent."22de"("ab"turned into"2"and"bc"turned into"2") is invalid as the substring chosen overlap.
Given a string word, return a list of all the possible generalized abbreviations of word. Return the answer in any order.
Example 1:
Input: word = "word"
Output: ["4","3d","2r1","2rd","1o2","1o1d","1or1","1ord","w3","w2d","w1r1","w1rd","wo2","wo1d","wor1","word"]
Example 2:
Input: word = "a"
Output: ["1","a"]
Constraints:
1 <= word.length <= 15wordconsists of only lowercase English letters.
Solution
Approach: Backtracking
Every letter of word is either kept or abbreviated. A choice for each letter gives exactly one abbreviation: a run of consecutive abbreviated letters becomes its length, and the rules (non-overlapping, non-adjacent substrings) are the same as saying that each maximal run is written as a single number. So there are exactly 2n abbreviations, one for each set of choices.
We build them with a recursive search dfs(i, cur, count):
curis the text written so far forword[0..i-1].countis the length of the current run of abbreviated letters just beforei, which is not written yet.
At each position there are two branches:
- Abbreviate
word[i]:dfs(i + 1, cur, count + 1). The run just gets longer. - Keep
word[i]: write the pending count (if it is not zero), then the letter, and calldfs(i + 1, cur + count + word[i], 0).
When i reaches the end, write the pending count (if any) and record cur.
The point of carrying count instead of writing digits right away is that two abbreviated letters in a row must become "2", not "11", which would be the invalid adjacent case. For "word", abbreviating everything gives "4", and keeping everything gives "word".
Complexity: O(n · 2n) time, since there are 2n results of length up to n, and O(n) extra space for the recursion, besides the output.
class Solution:
def generateAbbreviations(self, word: str) -> List[str]:
n = len(word)
answer = []
# cur: the abbreviation of word[:i] without its trailing count;
# count: how many letters right before i are abbreviated (not written yet).
def dfs(i: int, cur: str, count: int) -> None:
if i == n:
answer.append(cur + (str(count) if count else ""))
return
dfs(i + 1, cur, count + 1) # abbreviate word[i]: it joins the current run
dfs(i + 1, cur + (str(count) if count else "") + word[i], 0) # keep word[i]: the run ends
dfs(0, "", 0)
return answer