easy to understand (C++ 59 ms)


  • 0
    K

    The basic idea is to keep a hashmap to store the sorted string as keys and its index in the vector<string> as values;

    vector<vector<string>> groupAnagrams(vector<string>& strs) {
            vector<vector<string>>res;
    	vector<string>inner;
    	unordered_map<string, int>mp;
    	int n = strs.size();
    	string copy;
    	for (int i = 0; i < n; ++i)
    	{
    		copy = strs[i];
    		sort(copy.begin(), copy.end());
    		if (mp.find(copy) == mp.end())
    		{
    			inner.clear();
    			inner.push_back(strs[i]);
    			mp[copy] = res.size();
    			res.push_back(inner);
    		}
    		else res[mp[copy]].push_back(strs[i]);
    	}
    	return res;
        }
    

Log in to reply
 

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