Group Anagrams 题解
原创文章,拒绝转载
题目来源:https://leetcode.com/problems/group-anagrams/description/
Description
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
Solution
class Solution {
private:
struct cmp {
bool operator() (char a, char b) {
return a < b;
}
} cmpObj;
public:
vector<vector<string> > groupAnagrams(vector<string>& strArr) {
size_t size = strArr.size();
vector<vector<string> > res;
if (size == 0)
return res;
unordered_map<string, vector<string>> hs;
for (auto& str : strArr) {
string key = str;
sort(key.begin(), key.end(), cmpObj);
hs[key].push_back(str);
}
for (auto& item: hs) {
res.push_back(item.second);
}
return res;
}
};
解题描述
这道题题意是,给出一个字符串数组,将其中的字符串归类,归类的依据是每个同一类的字符串之间仅通过变换字符位置就可以互相转换。这样一个问题还是属于哈希的问题,我使用了底层实现为哈希表的STL容器unordered_map
来存储哈希项,对插入哈希表的字符串,计算哈希值的时候只需要对字符串排序。