My simple C++ code with two map,easily understand


  • 0
    W
    class Solution {
    public:
        vector<string> anagrams(vector<string>& strs) {
            vector<string> res;
            string temp;
            unordered_map<string,string> record;
            unordered_map<string,int> count;
            for(int i = 0;i < strs.size();i++){
                temp = strs[i];
                sort(temp.begin(),temp.end());
                if(record.find(temp) != record.end()){
                    if(count[temp] == 0){
                        res.push_back(record[temp]);
                        res.push_back(strs[i]);
                        count[temp]++;
                    }
                    else 
                    res.push_back(strs[i]);
                }
                else{
                    record[temp] = strs[i];
                    count[temp] = 0;
                }
            }
            return res;
        }
    };

Log in to reply
 

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