411. Minimum Unique Word Abbreviation (Hard)
A string such as "word"
contains the following abbreviations:
["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
Given a target string and a set of strings in a dictionary, find an abbreviation of this target string with the smallest possible length such that it does not conflict with abbreviations of the strings in the dictionary.
Each number or letter in the abbreviation is considered length = 1. For example, the abbreviation "a32bc" has length = 4.
Note:
- In the case of multiple answers as shown in the second example below, you may return any one of them.
- Assume length of target string = m, and dictionary size = n. You may assume that m ≤ 21, n ≤ 1000, and log2(n) + m ≤ 20.
Examples:
"apple", ["blade"] -> "a4" (because "5" or "4e" conflicts with "blade")
"apple", ["plain", "amber", "blade"] -> "1p3" (other valid answers include "ap3", "a3e", "2p2", "3le", "3l1").
Solution: 22ms
class Solution {
int n, candidates, bn, minlen, minab;
// 1: character
// 0: number
// Return the length of abbreviation given bit sequence
int abbrLen(int mask) {
int cnt = n;
// 3: 11
for (int b = 3; b < bn; b <<= 1) {
if ((mask & b) == 0) --cnt;
}
return cnt;
}
void dfs(vector<int>& dict, int bit, int mask) {
int len = abbrLen(mask);
if (len >= minlen) return;
bool match = true;
for (auto d: dict) {
if ((mask & d) == 0) {
match = false;
break;
}
}
if (match) {
minlen = len;
minab = mask;
} else {
for (int b = bit; b < bn; b <<= 1) {
if (candidates & b) dfs(dict, b << 1, mask+b);
}
}
}
public:
string minAbbreviation(string target, vector<string>& dictionary) {
n = target.size(), candidates = 0, bn = 1 << n, minlen = INT_MAX;
vector<int> dict;
for (auto w: dictionary) {
if (w.size() != n) continue;
int word = 0;
for (int i = 0; i < n; ++i) {
word <<= 1;
word += (target[i] == w[i]) ? 0 : 1;
}
dict.push_back(word);
candidates |= word;
}
dfs(dict,1,0);
string res;
// Reconstruct abbreviation from bit sequence
for (int i = n-1, pre = i; i >= 0; --i, minab >>= 1) {
if (minab & 1) {
if (pre - i > 0) res = to_string(pre-i)+res;
pre = i-1;
res = target[i]+res;
} else if (i == 0) res = to_string(pre-i+1)+res;
}
return res;
}
};