leeetcode 面试算法题 49. 字母异位词分组

66 阅读1分钟

给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。

字母异位词 是由重新排列源单词的所有字母得到的一个新单词。

 

示例 1:

输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]

示例 2:

输入: strs = [""]
输出: [[""]]

示例 3:

输入: strs = ["a"]
输出: [["a"]]

 

提示:

  • 1 <= strs.length <= 104
  • 0 <= strs[i].length <= 100
  • strs[i] 仅包含小写字母

原文链接:leetcode.cn/problems/gr…

题解

记录一种很牛逼的思路,质数的乘积。把a到z26个字母分别用不同的质数来表示,因为任意不同质数的乘积总是不同的,所以可以每一个字符串中的每一个字母代表的质数相乘,作为这个字符串的哈希表的键值。最后用哈希表的方式去求解酒可以了。

public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
    //字母对应质数map
    unordered_map<char, int> AlphtoPrime_Map;
    //根据字母出现频率 优化了一下 高频字母对应小质数
    int primeNum[26] = {5, 71, 31, 29, 2, 53, 59, 23, 11, 89, 79, 37, 41, 13, 7, 43, 97, 17, 19, 3, 47, 73, 61, 83, 67, 101};
    for (int i = 0; i < 26; ++ i) {
        AlphtoPrime_Map[i + 'a'] = primeNum[i];
    }

    //计算字符串对应的乘积key
    unordered_map<unsigned int,vector<string>> mp;
    unsigned int key;
    for(string str:strs){
    key = 1;
    for(int index = 0 ; index < str.size() ; index++){
    key *= AlphtoPrime_Map[str[index]];
    }
    mp[key].emplace_back(str);
    }

    //
    vector<vector<string>> result;
    for(auto it=mp.begin(); it !=mp.end() ; it++){
      result.emplace_back(it->second);
    }
    return result;
}
};