解题过程
其实一开始除了字母排序没什么思路,上网查了一下,试着写了写看
1.质数乘积
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<int> alphabet = {
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
};
unordered_map<long long, vector<string>> ans;
for (int i = 0; i < strs.size(); i++) {
long long hash = 1;
for (int j = 0; j < strs[i].length(); j++) {
hash *= alphabet[strs[i][j] - 'a'];
}
ans[hash].push_back(strs[i]);
}
vector<vector<string>> res;
for (auto it = ans.begin(); it != ans.end(); it++) {
res.push_back(it->second);
}
return res;
}
};
[“xyzzzzzzzzzzzz”,”zzzzzzzzzzzzyx”] 然后啪炸变量了
炸街来
于是改之
2.以字母计数作为索引
那样的话思路就是 遍历字符串→计数→按照计数分组
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<vector<int>,vector<string>> ans;
for (int i = 0; i < strs.size(); i++) {
vector<int> count={
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0};
for (int j = 0; j < strs[i].length(); j++) {
count[(int)(strs[i][j]-'a')]++;
}
ans[count].push_back(strs[i]);
}
vector<vector<string>> res;
for (auto it = ans.begin(); it != ans.end(); it++) {
res.push_back(it->second);
}
return res;
}
};
想法很美然后报错了
unordered_map默认不支持vector当键用
……fine
诶你说用array能行吗(写笔记之人骤然意识到)好吧也不行
改
3.把字母计数数组转化为字符串
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string,vector<string>> ans;
for (int i = 0; i < strs.size(); i++) {
vector<int> count={
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0};
string name;
for (int j = 0; j < strs[i].length(); j++) {
count[(int)(strs[i][j]-'a')]++;
}
for (int h = 0; h < 26; h++) {
name+=to_string(count[h]);
}
ans[name].push_back(strs[i]);
}
vector<vector<string>> res;
for (auto it = ans.begin(); it != ans.end(); it++) {
res.push_back(it->second);
}
return res;
}
};
[“bdddddddddd”,”bbbbbbbbbbc”]
依旧翻车
啧……原来不加分隔会歧义(from gpt大人)说的是会进位吗可恶
4.于是加上分隔符
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string,vector<string>> ans;
for (int i = 0; i < strs.size(); i++) {
vector<int> count={
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0};
string name;
for (int j = 0; j < strs[i].length(); j++) {
count[(int)(strs[i][j]-'a')]++;
}
for (int h = 0; h < 26; h++) {
name+=to_string(count[h]);
name+='#';
}
ans[name].push_back(strs[i]);
}
vector<vector<string>> res;
for (auto it = ans.begin(); it != ans.end(); it++) {
res.push_back(it->second);
}
return res;
}
};
写是写完了但是时间有点长(/(ㄒoㄒ)/~~
但是时间复杂度是,即便用上字符串排序也是
就这样吧(瘫
知·识·点(哆啦A梦音)
unordered_map需要哈希函数和相等比较器。- 默认情况下,标准库只为部分常见类型提供了默认哈希函数,例如整数、字符串等。
vector和array虽然可以比较相等,但默认不能直接作为unordered_map的 key。- 自定义哈希函数的作用是告诉
unordered_map:如何根据你的自定义类型计算哈希值。 - 哈希值不要求唯一;相等的 key 必须有相同的哈希值,而不同的 key 可以发生哈希冲突。