Share my C++ solutions, easy to understand


  • 1
    V
    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            vector<vector<string>> ret;
            int n = strs.size();
                
            multimap<string, string> mmap;
            int i = 0;
            
            for (i = 0; i < n; i++)
            {
                string s = strs[i];
                sort(s.begin(), s.end());
                
                mmap.insert(pair<string, string>(s, strs[i]));
            }
            
            multimap<string, string>::iterator iter = mmap.begin();
            int cnt = 0;
            
            while (iter != mmap.end())
            {
                vector<string> tmp;
                cnt = mmap.count(iter->first);
                
                for (i = 0; i < cnt; i++, iter++)
                {
                    tmp.push_back(iter->second);
                }
                
                ret.push_back(tmp);
            }
            
            return ret;
        }
    };

  • 3
    V

    The following is better:

    class Solution {
    public:
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            vector<vector<string>> ret;
            int n = strs.size();
                
            unordered_map<string, vector<string>> mmap;
            int i = 0;
            
            for (i = 0; i < n; i++)
            {
                string s = strs[i];
                sort(s.begin(), s.end());
                
                mmap[s].push_back(strs[i]);
            }
            
            for (auto it = mmap.begin(); it != mmap.end(); it++)
            {
                ret.push_back(it->second);
            }
            
            return ret;
        }
    };

Log in to reply
 

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