Wednesday, January 28, 2015

49 Anagrams

Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
class Solution {
public:
    vector<string> anagrams(vector<string> &strs) {
        vector<string> res;
        unordered_map<string, vector<string>> hmap;
        for (int i=0;i<strs.size();i++)
        {
            string temp = strs[i];
            sort(temp.begin(),temp.end());
            hmap[temp].push_back(strs[i]);
        }
        for (auto it = hmap.begin();it!=hmap.end();it++)
        {
            if (it->second.size()>1)
            {
                for (int j=0;j<it->second.size();j++)
                    res.push_back(it->second[j]);
            }
        }
        return res;
        
    }
};

No comments:

Post a Comment