lc320

Write a function to generate the generalized abbreviations of a word.

Example:

1
2
Given word = "word", return the following list (order does not matter):
["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3",

backtracking

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
unordered_map<string, vector<string>> mp;
public:
vector<string> generateAbbreviations(string word) {
string s = "";
mp[""].push_back("");
helper(word);
return mp[word];
}
vector<string> helper(string s) {
string res = "";
if (mp.find(s) != mp.end())
return mp[s];
int len = s.length();
res += s[0];
vector<string> rem = helper(s.substr(1));
for (auto rest: rem) {
mp[s].push_back(res+rest);
}
for (int i = 0; i < len; i++) {
res = to_string(i+1);
if (i < len-1) {
res += s[i+1];
vector<string> rem = helper(s.substr(i+2));
for (auto rest: rem)
mp[s].push_back(res+rest);
}
else mp[s].push_back(res);
}
return mp[s];
}
};