leetcode 49 字母异位词分组

个人代码:C++

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        //使用排序+哈希方法,对字母进行排序从而使异位单词还原成相同的词用于比较,然后通过哈希表确定每一组异位词的编号和总共异位词的组数;
        vector<string> strs2=strs;
        for(auto &s1:strs2){
            sort(s1.begin(),s1.end());
        }
        int flag=0,len=strs.size();
        unordered_map<string,int> um;
        for(int i=0;i<len;i++){
            if(um.count(strs2[i])==0){
                um[strs2[i]]=flag;flag++;
            }
        }
        vector<vector<string>>res(flag);
        for(int i=0;i<len;i++){
            res[um[strs2[i]]].push_back(strs[i]);
        }
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/joelwang/p/10559518.html