Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]
Note:
- For the return value, each inner list's elements must follow the lexicographic order.
- All inputs will be in lower-case.
// Usage of HashMap.
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
vector< vector<string> > groupAnagrams(vector<string>& strs) {
if(strs.size() == 0) return {{}};
vector< vector<string> > res;
unordered_map<string, vector<string> > map;
for(int i = 0; i < strs.size(); ++i) {
string tmp = strs[i];
sort(tmp.begin(), tmp.end()); // this is the key point.
auto iter = map.find(tmp);
if(iter == map.end()) {
map.insert({tmp, {strs[i]}}); // make_pair {}
} else {
(iter->second).push_back(strs[i]);
}
}
auto it = map.begin();
while(it != map.end()) {
sort(it->second.begin(), it->second.end()); // sort them in lexicographic order.
res.push_back(it->second);
it++;
}
return res;
}
int main(void) {
vector<string> inputs{"eat", "tea", "tan", "ate", "nat", "bat"};
vector< vector<string> > res = groupAnagrams(inputs);
for(int i = 0; i < res.size(); ++i) {
for(int j = 0; j < res[i].size(); ++j) {
cout << res[i][j] << endl;
}
cout << endl;
}
cout << endl;
}
本文介绍了一种使用哈希映射实现的高效算法来解决字谜游戏问题,即对一组字符串进行分组,将互为字谜(anagrams)的字符串归类到一起。文章通过具体的代码示例展示了如何利用C++语言中的`unordered_map`数据结构来实现这一算法,并确保输出结果遵循字典序排列。
498

被折叠的 条评论
为什么被折叠?



