short c++ solution using sort and map


  • 0
    Z
    vector<vector<string> > groupAnagrams(vector<string>& strs) {
            vector<vector<string> > res;
            if(strs.empty()) return res;
            map<string,int> m;
            int pos = 0;
            for(int i=0;i<strs.size();++i)
            {
            	string tmp(strs[i]);
            	sort(tmp.begin(),tmp.end());
            	map<string,int>::iterator it = m.find(tmp);
            	if(it != m.end())  //find
            	{
            		res[it->second].push_back(strs[i]);
            	}
            	else{
            		vector<string> v;
            		v.push_back(strs[i]);
            		res.push_back(v);
            		m.insert(pair<string,int>(tmp,pos++));
            	}
            }
            return res;
        }

Log in to reply
 

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