Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
minimum-unique-word-abbreviation.cpp 1.95 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2016-10-06 23:24 +08:00 . Update minimum-unique-word-abbreviation.cpp
// Time: O(2^n)
// Space: O(n)
class Solution {
public:
string minAbbreviation(string target, vector<string>& dictionary) {
vector<int> diffs;
dictionary_to_diffs(target, dictionary, &diffs);
if (diffs.empty()) {
return to_string(target.length());
}
int bits = (1 << target.length()) - 1;
for (int i = 0; i < (1 << target.length()); ++i) {
if (all_of(diffs.begin(), diffs.end(), [&i](int d) { return d & i; } )) {
if (bits_len(target, i) > bits_len(target, bits)) {
bits = i;
}
}
}
return bits_to_abbr(target, bits);
}
private:
void dictionary_to_diffs(const string& target, const vector<string>& dictionary,
vector<int> *diffs) {
for (const auto& word : dictionary) {
if (word.length() != target.length()) {
continue;
}
int bits = 0;
for (int i = 0; i < word.length(); ++i) {
if (target[i] != word[i]) {
bits |= 1 << i;
}
}
diffs->emplace_back(bits);
}
}
int bits_len(const string& target, int bits) {
int sum = 0;
for (int i = 0; i < target.length() - 1; ++i) {
if (((bits >> i) & 3) == 0) {
++sum;
}
}
return sum;
}
string bits_to_abbr(const string& target, int bits) {
string abbr;
int pre = 0;
for (int i = 0, prev = 0; i < target.length(); ++i, bits >>= 1) {
if (bits & 1) {
if (i - pre > 0) {
abbr += to_string(i - pre);
}
pre = i + 1;
abbr.push_back(target[i]);
} else if (i == target.length() - 1) {
abbr += to_string(i - pre + 1);
}
}
return abbr;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助