(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;
    }
};

 

转载于:https://www.cnblogs.com/Bella2017/p/11260514.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值