convert anagrams into the same string without sort


  • 0
    B
        string convert(string& s) {
            string ret;
            vector<int> A(26, 0);
            
            for(int i = 0; i < s.size(); ++i) {
                A[s[i]-'a'] += 1;
            }
            
            for(int i = 0; i < 26; ++i) {
                if(A[i]) {
                    ret += to_string(A[i])+(char)('a'+i);
                }
            }
            
            return ret;
        }
        
        vector<vector<string>> groupAnagrams(vector<string>& strs) {
            int num = strs.size(), i;
            string temp;
            map<string, vector<string>> mymap; // store grouped results
            map<string, vector<string>>::iterator it;
            vector<vector<string>> ret;
            
            for(i = 0; i < num; ++i) {
                temp = convert(strs[i]);
                it = mymap.find(temp);
                if(it == mymap.end()) {
                    mymap[temp] = vector<string>{strs[i]};
                } else {
                    mymap[temp].push_back(strs[i]);
                }
            }
            
            for(it = mymap.begin(); it != mymap.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.