[LeetCode] 49. Group Anagrams

来源:互联网 发布:java培训有哪些骗局 编辑:程序博客网 时间:2024/05/16 06:25

思路:
维护一个哈希表, key是一个字符串, 是各个数据字符串的sort串, 对应的是同组字符串所存数组的下标. 这题模拟一下就可以, 很简单的. 看到网上还有用质数做的黑魔法, 回头可以研究一下.

vector<vector<string>> groupAnagrams(vector<string>& strs) {    vector<vector<string>> res;    unordered_map<string, int> hash;    for (int i = 0; i < strs.size(); i++) {        string temp = strs[i];        sort(temp.begin(), temp.end());        if (! hash.count(temp)) {            vector<string> candidate(1, strs[i]);            res.push_back(candidate);            hash[temp] = res.size() - 1;        }        else             res[hash[temp]].push_back(strs[i]);    }    return res;}
0 0
原创粉丝点击