Tuesday, December 15, 2015

49. Group Anagrams -M

Q:
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]
Note:
  • All inputs will be in lowercase.
  • The order of your output does not matter.
A:


用map来group,最终再利用Collection来保存回去

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        map<string,vector<string>> mp;
        for(auto s:strs){
            string key = s;
            sort(key.begin(), key.end());
            if(mp.find(key) == mp.end()){
                mp[key] = vector<string>();
            }
            mp[key].push_back(s);
        }
        vector<vector<string>> res;
        for(const auto& tmp : mp){
            res.push_back(tmp.second);
        }
        return res;
    }
};



Mistakes:



No comments:

Post a Comment