Leetcode 49. Group Anagrams

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Group Anagrams

2. Solution

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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;
}
};

Reference

  1. https://leetcode.com/problems/group-anagrams/description/
如果有收获,可以请我喝杯咖啡!