Leetcode:49. Group Anagrams

Description

Given an array of strings, group anagrams together.

Example

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], 
Return:

[
    ["ate", "eat","tea"],
    ["nat","tan"],
    ["bat"]
]

思路

  • 思路一:用map实现,先将每个字符串转换为一个map<char,int>,然后通过一个map<map<char,int>, int> 判断是否重复,然后在此基础上操作
  • 思路二,unordered_map<string,int>实现

代码

  • map<map<char,int>, int> 实现,102ms
class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> res;
        int len = strs.size();
        if(len == 0) return res;
        
        map<map<char, int>, int> Map;
        map<char, int> tmpMap;
        int start = 0;
        for(int i = 0; i < len; ++i){
            tmpMap.clear();
            for(int j = 0; j < strs[i].size(); ++j)
                tmpMap[strs[i][j]]++;
                
            if(Map.count(tmpMap) > 0)
                res[Map[tmpMap]].push_back(strs[i]);
            else{
                vector<string> strTmp;
                strTmp.push_back(strs[i]);
                res.push_back(strTmp);
                Map.insert(pair<map<char,int>, int>(tmpMap, start));
                start++;
            }
        }
        
        return res;
    }
};
  • unordered_map <string, int> 实现,39ms
class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> res;
        int len = strs.size();
        if(len == 0) return res;
        
        unordered_map<string, int> Map;
        string tmpMap;
        int start = 0;
        for(int i = 0; i < len; ++i){
            tmpMap = strs[i];
            sort(tmpMap.begin(), tmpMap.end());
            //for(int j = 0; j < strs[i].size(); ++j)
             //   tmpMap[strs[i][j]]++;
                
            if(Map.count(tmpMap) > 0)
                res[Map[tmpMap]].push_back(strs[i]);
            else{
                vector<string> strTmp;
                strTmp.push_back(strs[i]);
                res.push_back(strTmp);
                Map.insert(pair<string, int>(tmpMap, start));
                start++;
            }
        }
        
        return res;
    }
};
原文地址:https://www.cnblogs.com/lengender-12/p/6848289.html