c_cpp 给定一组单词,返回给定集合中的anagrams集合
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 给定一组单词,返回给定集合中的anagrams集合相关的知识,希望对你有一定的参考价值。
vector<string> get_collection_of_anagrams(const vector<string> &words) {
vector<string> res;
if(words.empty()) return res;
unordered_map<string, vector<int>> hash;
for(int i=0; i<words.size(); i++) {
string s = words[i];
sort(s.begin(), s.end());
if(hash.find(s) != hash.end())
hash[s].push_back(i);
else {
vector<int> v = {i};
hash[s] = v;
}
}
for(auto p : hash) {
if(p.second.size() >= 2) {
for(int i : p.second)
res.push_back(words[i]);
}
}
return res;
}
// another similar version
vector<string> get_collections_of_anagrams(const vector<string>& words) {
vector<string> result;
int n = words.size();
if(n == 0 || n == 1)
return result;
unordered_map<string, vector<string>> hash;
for(string word : words) {
string sorted = word;
sort(sorted.begin(), sorted.end());
if(hash.find(sorted) == hash.end()) {
vector<string> vs;
vs.push_back(word);
hash[sorted] = vs;
}
else { /* consider duplications?
vector<string> *v = &hash[sorted];
if(v->find(word) == v->end())
v->push_back(word); */
hash[sorted].push_back(word);
}
}
for(auto& p : hash) {
if(p.second.size() >= 2) {
for(string& s : p.second)
result.push_back(s);
}
}
return result;
}
以上是关于c_cpp 给定一组单词,返回给定集合中的anagrams集合的主要内容,如果未能解决你的问题,请参考以下文章