49. Group Anagrams

来源:互联网 发布:fliqlo mac 编辑:程序博客网 时间:2024/05/23 00:02

Given an array of strings, group anagrams together.

For example, given: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
Return:

[  ["ate", "eat","tea"],  ["nat","tan"],  ["bat"]]

这道题使用哈希表,要灵活选择键值

解题代码

vector<vector<string>> groupAnagrams(vector<string>& strs) {    vector<vector<string>> ret;    unordered_map<string, vector<string>> memo;    for (int i = 0; i < strs.size(); i++){        string s = strs[i];        // 要找Anagrams,先排个序寻找其不变量        sort(s.begin(), s.end());        if (memo.find(s) != memo.end()){            memo[s].push_back(strs[i]); // 找到就push        }        else{ // 没有找到就新建一个vector放起来            memo[s] = vector<string>(1, strs[i]);        }    }    // 放到ret中作为结果返回    for (auto& my_map : memo){        ret.push_back(my_map.second);    }    return ret;}