(hash) leetcode 49. Group Anagrams

思路:哈希表,用map实现,(key, value) = (strs[i], index).

将字符串按字典序排序后,若能在map中找到相应的字符串,则对应value+1(value存储的是单词中同构体集合在output中的index),如 ["ate", "eat", "tea"] 对应索引为0; ["nat", tan"] 对应索引为1...

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        //hash
        vector<vector<string>> result;
        map<string, int> index;
        int cnt = 0;   //记录anagram 个数
        for(int i=0; i<strs.size(); ++i){
            string tmp = strs[i];
            sort(tmp.begin(), tmp.end());  //按字典序排列
            if(index.find(tmp) == index.end()){
                //未在map中找到tmp
                index[tmp] = cnt;
                cnt++;
                vector<string> tmpstr;
                tmpstr.push_back(strs[i]);
                result.push_back(tmpstr);
            }
            else
                result[index[tmp]].push_back(strs[i]);
        }
        return result;
    }
};
class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> res;    //返回值
        unordered_map<string, vector<string>> m;   //字符串与它的同构字符串之间的映射
        for(string str: strs){
            string t = str;
            sort(t.begin(),t.end());
            m[t].push_back(str);
        }
        for(auto a:m)
            res.push_back(a.second);
        return res;
    }
};

 

posted @ 2019-07-28 19:18  爱学英语的程序媛  阅读(152)  评论(0编辑  收藏  举报