Group Anagrams

来源:互联网 发布:淘宝金三塔官方旗舰店 编辑:程序博客网 时间:2024/05/17 07:11

1 问题描述
Given an array of strings, group anagrams together.

For example, given: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
Return:
[
[“ate”, “eat”,”tea”],
[“nat”,”tan”],
[“bat”]
]
2解决思路
思路1:
可以对该序列中的所有字符串进行排序,然后使用hash函数,哈希值相同的元素则对应原来的字符串只能是顺序不同。
思路2:将字符串中每个数字与不同的素数对应,比如说a映射到2,b映射到3,c映射到5。字符串abc的映射值为30. 由于整数环是唯一分解环,那么对应的一个整数可以唯一分解为若干个素数的乘积,如30只能分解为2*3*5,因此只有abc,acb,bac,bca,cab,cba等与30相对应。这种哈希方式可以保证原来的元素只能有顺序不同。因此能够找到那些字母相同,而顺序不同的值。

3实现

vector<vector<string>> groupAnagrams(vector<string>& strs) {        int prime[] = { 2, 3, 5, 7,11, 13, 17, 19, 23, 29, 31, 41, 43, 47, 53 ,59,61,67,71,73,79,83,89,97,101,103};//26个素数        vector<vector<string>> res;        unordered_map<int, vector<int>> map;        for (int i = 0; i < strs.size(); i++){            string s = strs[i];            int product = 1;            for (int j = 0; j < s.size(); j++){                product *=prime[ s[j] - 'a'];            }            if (map.count(product) == 0){                map[product] = { i };            }            else                map[product].push_back(i);        }        for (auto itr = map.begin(); itr != map.end(); itr++){            vector<string> s;                for (size_t j = 0; j != itr->second.size(); j++){                    string temp = strs.at(itr->second.at(j));                    s.push_back(temp);                }                res.push_back(s);            }        return res;        }

4 总结
这种方式的算法复杂度是优于排序加哈希的实现方式的,但是这种算法的问题在于当字符串很长时,求他们的乘积可能会溢出。

0 0