-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnagrams.cc
104 lines (72 loc) · 1.52 KB
/
Anagrams.cc
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
100
101
102
#include <vector>
#include <string>
#include <iostream>
using std::vector;
using std::string;
using std::cout;
using std::endl;
#include <cstdlib>
using std::atoi;
struct ListNode{
int val;
ListNode *next;
ListNode(int x):val(x), next(NULL){}
};
#include <algorithm>
#include <cstring>
#include <unordered_map>
#include <map>
template<typename T_>
class my_hash;
template<>
class my_hash<string>{
public:
std::size_t operator()(const string &s)const{
auto ts = s;
std::sort(ts.begin(), ts.end());
return std::hash<string>()(ts);
}
};
class Solution{
public:
vector<string> anagrams(vector<string> &strs){
std::map<std::size_t, int> mp;
for(auto &s: strs){
auto k = my_hash<string>()(s);
auto fd = mp.find(k);
if(fd != mp.end()){
fd->second += 1;
}else{
mp[k] = 1;
}
}
vector<string> ans;
for(auto &s: strs){
auto k = my_hash<string>()(s);
if(mp[k] > 1){
ans.push_back(std::move(s));
}
//ans.push_back(std::move(s));
}
return ans;
}
};
int main(){
Solution slu;
using std::cin;
vector<string> strs = {
"dog",
"cat",
"god",
"tac",
"hello",
"nice",
//"nice",
};
auto ans = slu.anagrams(strs);
for(auto &s: ans){
cout << s << " ";
}
cout << endl;
return 0;
}