
class Solution {
public:
static bool cmp(string a, string b){
int sum_a = 0;
int sum_b = 0;
sort(a.begin(), a.end());
sort(b.begin(), b.end());
return a<b;
// for(int j = 0; j < a.length(); j++){
// sum_a = sum_a + (a[j]-'0');
// }
// for(int j = 0; j < b.length(); j++){
// sum_b = sum_b + (b[j]-'0');
// }
// return sum_a<sum_b;
}
// int sumstr(string a){
// int sum = 0;
// for(int j = 0; j < a.length(); j++){
// sum = sum + (a[j]-'0');
// }
// return sum;
// }
int judge(string a,string b){
sort(a.begin(), a.end());
sort(b.begin(), b.end());
if(a==b)
return true;
else
return false;
}
vector<vector<string>> groupAnagrams(vector<string>& strs) {
// cmp算法中对字符串进行排序后再比较大小。
sort(strs.begin(), strs.end(),cmp);
for(int i = 0; i < strs.size(); i++){
cout<<"str: "<<strs[i]<<endl;
}
vector<vector<string>> res;
if(strs.size()==0)
return res;
int count = 0;
while(count<strs.size()){
vector<string> temp;
temp.push_back(strs[count]);
// judge对字符串排序后再判断大小
while((count+1)<strs.size()&&judge(strs[count],strs[count+1])){
count++;
temp.push_back(strs[count]);
}
count++;
res.push_back(temp);
}
return res;
// for(int i = 0; i < strs.size(); i++){
// vector<string> temp;
// if(sumstr(str[i]))
// }
}
};
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
// 变形后的哈希表
unordered_map<string, vector<string>> in_map;
vector<vector<string>> res;
for(int i = 0; i < strs.size(); i++){
string temp = strs[i];
sort(temp.begin(), temp.end());
in_map[temp].push_back(strs[i]);
}
// unordered_map<string, vector<string>>::iterator it;
// 注意 哈希表的遍历方式
for(auto it = in_map.begin(); it!=in_map.end(); it++){
cout<<"it"<<endl;
res.push_back(it->second);
}
// for(int i = 0; i < in_map.size(); i++){
// res.push_back(in_map[i]);
// }
return res;
}
};
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> un_map;
// unordered_map底层是哈希表 ,时间复杂度O(1);
// map底层是平衡数O(logn)
for(auto str: strs){
string key = str;
sort(key.begin(), key.end());
un_map[key].push_back(str);
}
vector<vector<string>> res;
for(auto item:un_map){
res.push_back(item.second);
}
return res;
}
};