Valid solution using unordered_map c++


  • 0
    P
    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
        
            vector< vector<string> > res;
        
        	// Associate to each anagram the index where it has to be added
        	int idx = 0;
        	unordered_map<std::string, int> idxMap;
        
        	for(auto& s : strs)
        	{
        		std::string ss(s);
        		sort(ss.begin(), ss.end());
        		
        		auto isInIdxMap = idxMap.find(ss);
        
        		if(isInIdxMap == idxMap.end())
        		{
        			idxMap[ss] = idx;
        			res.push_back(vector<string>(1, s));
        			++idx;
        		}
        		else
        			res[isInIdxMap->second].push_back(s);
        	}
        	
            for(auto& vs : res)
        	{
        		std::sort(vs.begin(), vs.end(), [](const string& a, const string& b)->bool{
        				auto minSize = std::min(a.size(), b.size());
        				for(int i = 0; i < minSize; i++)
        				{
        					if(a[i] < b[i])
        						return true;
        					else if(b[i] < a[i])
        						return false;
        					else
        						continue;
        				}
        				return true;
        			});
        	}
        
        	return res;
        }
    }
    

    ;


Log in to reply
 

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