Description:
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
分析:
Anagram(回文构词法)是指打乱字母顺序从而得到新的单词,比如 “dormitory” 打乱字母顺
序会变成 “dirty room” , “tea” 会变成”eat”。
回文构词法有一个特点:单词里的字母的种类和数目没有改变,只是改变了字母的排列顺序。
因此,将几个单词按照字母顺序排序后,若它们相等,则它们属于同一组 anagrams 。
代码:
#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
vector<string> Anagrams(vector<string> str)
{
unordered_map<string, vector<string>> group;
for (const auto &s : str) //利用哈希原理
{
string key = s;
sort(key.begin(), key.end());
group[key].push_back(s); //将所有键值相同的添加到一起
}
//输出anagrams
vector<string> result;
for (auto it = group.cbegin(); it != group.cend(); it++) {
if (it->second.size() > 1)
result.insert(result.end(), it->second.begin(), it->second.end());
}
return result;
}
int main()
{
vector<string> str = { "dirtyroom", "tea", "eat", "dormitory","aet","mooridty","makefile","filemake"};
vector<string> result = Anagrams(str);
cout << "The result is: " << endl;
for (const auto &s : result)
{
cout<< s << " ";
}
cin.get();
return 0;
}
测试: