-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path49. Group Anagrams.cpp
99 lines (86 loc) · 2.1 KB
/
49. Group Anagrams.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
All inputs will be in lowercase.
The order of your output does not matter.
Solution one using built in sort, and store in an unordered_map
Solution two using hand write sorting to optimize
Solution three using a trick to avoid copying and speed up
*/
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> hash;
for ( auto &a: strs )
{
string temp = a;
sort( temp.begin(), temp.end() );
hash[temp].push_back( a );
}
vector<vector<string>> res;
for ( auto &a: hash )
{
res.push_back( a.second );
}
return res;
}
};
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> hash;
for ( auto &a: strs )
{
hash[CountSort( a )].push_back( a );
}
vector<vector<string>> res;
for ( auto &a: hash )
{
res.push_back( a.second );
}
return res;
}
private:
string CountSort( string& s )
{
int n = s.size();
int counter[26] = {0};
for ( int i = 0; i < n; ++i )
{
counter[s[i] - 'a']++;
}
string temp;
for ( int i = 0; i < 26; ++i )
{
temp += string( counter[i], i + 'a' );
}
return temp;
}
};
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, int> hash;
vector<vector<string>> res;
for ( auto &a: strs )
{
string t = a;
sort( t.begin(), t.end() );
if ( !hash.count( t ) )
{
hash[t] = res.size();
res.push_back( {} );
}
res[hash[t]].push_back( a );
}
return res;
}
};