Unique Generalized Abbreviations (hard)
Problem Statement
Given a word, write a function to generate all of its unique generalized abbreviations.
A generalized abbreviation of a word can be generated by replacing each substring of the word with the count of characters in the substring. Take the example of “ab” which has four substrings: “”, “a”, “b”, and “ab”. After replacing these substrings in the actual word by the count of characters, we get all the generalized abbreviations: “ab”, “1b”, “a1”, and “2”.
Note: All contiguous characters should be considered one substring, e.g., we can’t take “a” and “b” as substrings to get “11”; since “a” and “b” are contiguous, we should consider them together as one substring to get an abbreviation “2”.
Example 1:
Input: "BAT"
Output: "BAT", "BA1", "B1T", "B2", "1AT", "1A1", "2T", "3"
Example 2:
Input: "code"
Output: "code", "cod1", "co1e", "co2", "c1de", "c1d1", "c2e", "c3", "1ode", "1od1", "1o1e", "1o2",
"2de", "2d1", "3e", "4"
Try it yourself
Try solving this question here:
import java.util.*;class GeneralizedAbbreviation {public static List<String> generateGeneralizedAbbreviation(String word) {List<String> result = new ArrayList<String>();// TODO: Write your code herereturn result;}public static void main(String[] args) {List<String> result = GeneralizedAbbreviation.generateGeneralizedAbbreviation("BAT");System.out.println("Generalized abbreviation are: " + result);result = GeneralizedAbbreviation.generateGeneralizedAbbreviation("code");System.out.println("Generalized abbreviation are: " + result);}}
Solution
This problem follows the Subsets pattern and can be mapped to Balanced Parentheses. We can follow a similar BFS approach.
Let’s take Example-1 mentioned above to generate all unique generalized abbreviations. Following a BFS approach, we will abbreviate one character at a time. At each step, we have two options:
- Abbreviate the current character, or
- Add the current character to the output and skip the abbreviation.
Following these two rules, let’s abbreviate BAT
:
- Start with an empty word: “”
- At every step, we will take all the combinations from the previous step and apply the two abbreviation rules to the next character.
- Take the empty word from the previous step and add the first character to it. We can either abbreviate the character or add it (by skipping abbreviation). This gives us two new words:
_
,B
. - In the next iteration, let’s add the second character. Applying the two rules on
_
will give us_ _
and1A
. Applying the above rules to the other combinationB
gives usB_
andBA
. - The next iteration