Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
word-abbreviation.cpp 1.74 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2017-03-19 18:50 +08:00 . Update word-abbreviation.cpp
// Time: O(n * l) ~ O(n^2 * l^2)
// Space: O(n * l)
class Solution {
public:
vector<string> wordsAbbreviation(vector<string>& dict) {
unordered_map<string, unordered_set<string>> abbr_to_word;
unordered_map<string, string> word_to_abbr;
for (const auto& word : dict) {
const auto prefix = word.substr(0, 1);
abbr_to_word[toAbbr(prefix, word)].emplace(word);
}
for (const auto& kvp : abbr_to_word) {
if (kvp.second.size() > 1) {
for (const auto& word : kvp.second) {
for (int i = 2; i < word.length(); ++i) {
const auto prefix = word.substr(0, i);
if (isUnique(prefix, kvp.second)) {
word_to_abbr[word] = toAbbr(prefix, word);
break;
}
}
}
} else {
word_to_abbr[*kvp.second.begin()] = kvp.first;
}
}
vector<string> result;
for (const auto& word : dict) {
result.emplace_back(word_to_abbr[word]);
}
return result;
}
private:
bool isUnique(const string& prefix, const unordered_set<string>& words) {
return 1 == count_if(words.begin(), words.end(),
[&prefix](const string& word) {
return !word.compare(0, prefix.length(), prefix);
});
}
string toAbbr(const string& prefix, const string& word) {
string abbr = prefix;
abbr += to_string(word.length() - 1 - prefix.length());
abbr += word.back();
return abbr.length() < word.length() ? abbr : word;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助