Leetcode每日一题:49.group-anagrams(字母异位词分组)_hash
这道题我认为题目没有写清楚,测试用例中两个完全相同的字符串也归为一组,然而从题意中我们会认为这两个字符串只需放入一个即可

解题思路:

	方法1:利用hash + map 先用hash判断字符串是否相同 以及相同时该插入vector的位置
	方法2:利用sort + map 先用sort排序字符串 然后在map中找到该插入vector的位

Leetcode每日一题:49.group-anagrams(字母异位词分组)_哈希_02

//方法一 hash+map
class Solution {
public:
    int hash1(string s) //hash判断字母是否相同
    {
        long res1=1,res2=2;
        int len = s.size();
        if (len == 0)
            return -1;
         //这里傻傻的自己尝试hash解决冲突 , 其实用质数当因子就可以解决,一般来说无冲突
        for (int i = 0; i < len; i++)
        {
            res1 = res1 * (s[i]);
            if (res1 > INT_MAX)
                res1 = res1 % INT_MAX;
        }
        for (int i = 0; i < len; i++)
        {
            res2 = res2 * (s[i] +len);
            if (res2 > INT_MAX)
                res2 = res2 % INT_MAX;
        }
        return res1+res2;
        
    }
    vector<vector<string>> groupAnagrams(vector<string> &strs)
    {
        int len = strs.size();
        vector<vector<string>> res;
        if (len == 0)
            return res;
        map<int, bool> mp1; //hash1,是否出现
        map<int, int> mp2;//hash1,序号
        int count = 0;
        for (auto s : strs)
        {
            int a = hash1(s);
            if (mp1[a] == 0) //没出现过该字符串
            {
                mp1[a] = true;
                mp2[a] = count++;
                vector<string> temp;
                temp.push_back(s);
                res.push_back(temp);
                continue;
            }
            //出现过
            res[mp2[a]].push_back(s);
        }
        return res;
    }
};

建立hash表
int primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101,103,105};
然后 res *= primes[s[i]-‘a’];
Leetcode每日一题:49.group-anagrams(字母异位词分组)_i++_03
写的时候感觉效率应该会提升,实际上并不高;由此可见hash的效率

//方法二
vector<vector<string>> groupAnagrams(vector<string> &strs)
{
    vector<vector<string>> res;
    map<string,int> mp;//<字符串,下标>
    int sub=0;//用于找到插入的下标
    string temp;
    for(auto s:strs)
    {
        temp=s;
        sort(temp.begin(),temp.end());//排序 两个相同的字符串 排序结果一致
        if(mp.count(temp))
        {
            res[mp[temp]].push_back(s);
        }
        else
        {
            vector<string> vs;
            vs.push_back(s);
            res.push_back(vs);
            mp[temp]=sub++;
        }
    }
    return res;
}