320. Generalized Abbreviation (Medium)
Write a function to generate the generalized abbreviations of a word.
Example:
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", "4"]
Solution: Bit Manipulation
version 1: 49ms
这道题让我们对一个单词进行部分简写,简写的规则是若干个字母可以用数字来表示,但是不能有两个相邻的数字,具体可以参考题目中给的例子,根据我以往的经验,这种列举所有情况的必定是要用DFS来写的,但是我一时半会又没想到该咋递归,后来我数了一下题目中给的例子的所有情况的个数,是16个,而word有4个字母,刚好是2的4次方,这是巧合吗,当然不是,后来我又发现如果把0到15的二进制写出来,每一个可以对应一种情况,如下所示:
0000 word
0001 wor1
0010 wo1d
0011 wo2
0100 w1rd
0101 w1r1
0110 w2d
0111 w3
1000 1ord
1001 1or1
1010 1o1d
1011 1o2
1100 2rd
1101 2r1
1110 3d
1111 4
那么我们就可以观察出规律,凡是0的地方都是原来的字母,单独的1还是1,如果是若干个1连在一起的话,就要求出1的个数,用这个数字来替换对应的字母,既然规律找出来了,那么代码就很好写了,如下所示:
vector<string> generateAbbreviations(string word) {
vector<string> res;
int len = word.size(), n = pow(2, len);
for (int i = 0; i < n; ++i) {
int cnt = 0, t = i;
string out;
for (int j = 0; j < len; ++j) {
if (t & 1 == 1) {
++cnt;
if (j == len-1) out += to_string(cnt);
} else {
if (cnt) {
out += to_string(cnt);
cnt = 0;
}
out += word[j];
}
t >>= 1;
}
res.push_back(out);
}
return res;
}
version 2: 53ms
我们可以对上面代码稍稍改写一下,变的稍微简洁一点:
vector<string> generateAbbreviations(string word) {
vector<string> res;
int len = word.size(), n = pow(2, len);
for (int i = 0; i < n; ++i) {
int cnt = 0;
string out;
for (int j = 0; j < len; ++j) {
if ((i >> j) & 1) ++cnt;
else {
if (cnt) {
out += to_string(cnt);
cnt = 0;
}
out += word[j];
}
}
if (cnt) out += to_string(cnt);
res.push_back(out);
}
return res;
}
Solution 2: Backtracking
那么迭代的写法看完了,来考虑一些递归的写法吧,上网搜了一下,发现下面三种写法比较容易理解,
version 1: 42ms
class Solution {
public:
vector<string> generateAbbreviations(string word) {
vector<string> res{word};
dfs(word, 0, res);
return res;
}
void dfs(string word, int pos, vector<string>& res) {
for (int i = pos; i < word.size(); ++i) { // length
for (int j = 1; i+j <= word.size(); ++j) {
string t = word.substr(0,i);
t += to_string(j) + word.substr(i+j);
res.push_back(t);
// pos: next start position
dfs(t, i+to_string(j).size()+1, res);
}
}
}
};
version 2: 33ms
class Solution {
public:
vector<string> generateAbbreviations(string word) {
vector<string> res;
dfs(word, 0, 0, "", res);
return res;
}
void dfs(string word, int pos, int cnt, string out, vector<string>& res) {
if (pos == word.size()) {
if (cnt) out += to_string(cnt);
res.push_back(out);
return;
}
dfs(word, pos+1, cnt+1, out, res);
dfs(word, pos+1, 0, out+(cnt ? to_string(cnt):"")+word[pos], res);
}
};
version 3: 139ms
vector<string> generateAbbreviations(string word) {
vector<string> res;
res.push_back(word.size() == 0 ? "":to_string(word.size()));
for (int i = 0; i < word.size(); ++i) {
for (auto a: generateAbbreviations(word.substr(i+1))) {
string left = i ? to_string(i):"";
res.push_back(left+word.substr(i,1)+a);
}
}
return res;
}