分类:algorithm| 发布时间:2016-10-14 11:05:00
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> ret;
unordered_map<string, int> m;
for (auto str: strs) {
auto tmp = str;
sort(tmp.begin(), tmp.end());
if (m.count(tmp)) {
ret[m[tmp]].push_back(str);
} else {
m[tmp] = ret.size();
ret.push_back({str});
}
}
return ret;
}
};