给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]
说明:
所有输入均为小写字母。
不考虑答案输出的顺序。
通过次数80,334提交次数129,632
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/group-anagrams
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
还是利用hash,这道题的难点在于,如何对字母位置不同的字符串hash为同一个值,最直观的思路就是进行排序,这样每个字母不同的字符串就变成了相同的字符串,直接插入到map之中即可,这也是最终使用的方法。但是有更快的方式,即通过某一种不会冲突的方式,将满足要求的字符串唯一的表示出来即可。(另说)
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string,int> hash;
int len = strs.size();
vector<vector<string>> ret;
int count =0;
for(int i = 0;i<len;i++)
{
string temp = strs[i];
sort(temp.begin(),temp.end());
unordered_map<string,int>::iterator it;
it = hash.find(temp);
if(it!=hash.end())
{
ret[it->second].push_back(strs[i]);
}
else
{
vector<string> st;
st.push_back(strs[i]);
ret.push_back(st);
hash.insert(pair<string,int>(temp,count));
count++;
}
}
return ret;
}
};