文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
Group Anagrams2. Solution
- Version 1
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> result;
unordered_map<string, vector<string>> m;
for(string s : strs) {
string temp = s;
sort(temp.begin(), temp.end());
if(m.find(temp) != m.end()) {
m[temp].push_back(s);
}
else {
vector<string> anagrams;
anagrams.push_back(s);
m[temp] = anagrams;
}
}
for(auto iter: m) {
result.push_back(iter.second);
}
return result;
}
};
- Version 2
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> result;
unordered_map<string, vector<string>> m;
for(string s : strs) {
string temp = s;
sort(temp.begin(), temp.end());
m[temp].push_back(s);
}
for(auto iter: m) {
result.push_back(iter.second);
}
return result;
}
};
网友评论