C++ Solution with Using Hash


  • 0
    M
    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            vector<vector<string> > ans;
            unordered_map<string, int> nmap;
            for(int i = 0; i < strs.size(); i++) {
                string tmpstr = strs[i];
                sort(tmpstr.begin(),tmpstr.end());
                if(nmap[tmpstr] == 0) nmap[tmpstr] = nmap.size();
                if(nmap[tmpstr] > ans.size()) {
                    vector<string> tmp;
                    tmp.push_back(strs[i]);
                    ans.push_back(tmp);
                } else ans[nmap[tmpstr]-1].push_back(strs[i]);
            }
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.