-
Notifications
You must be signed in to change notification settings - Fork 0
/
anagram.cc
77 lines (76 loc) · 2.27 KB
/
anagram.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
#include<iostream>
#include<map>
#include<string>
}
#include<algorithm>
using namespace std;
class Solution {
public:
vector<string> anagrams(vector<string> &strs) {
int n = strs.size();
if (n < 2) return vector<string>();
vector<string> ret;
vector<string> ref = strs;
for (int i = 0; i < n; i++) {
sort(ref[i].begin(), ref[i].end());
}
unordered_map<string, int> hash;
for (int i = 0; i < n; i++) {
if (hash.count(ref[i]) == 0) {
hash[ref[i]] = i;
} else {
if (hash[ref[i]] != -1) {
ret.push_back(strs[hash[ref[i]]]);
hash[ref[i]] = -1;
}
ret.push_back(strs[i]);
}
}
return ret;
}
//------------------------------------------------//
vector<string> anagrams(vector<string> &strs) {
int n = strs.size();
vector<string> _strs = strs;
if (!n) return vector<string>();
bool first = true;
for (auto i = 0; i < n; ++i) sort(_strs[i].begin(), _strs[i].end());
unordered_map<string, int> hash;
vector<string> ret;
for (auto i = 0; i < n; ++i) {
if (hash.count(_strs[i]) > 0) {
if (first) {
ret.push_back( strs[hash[_strs[i]]] );
first = false;
}
ret.push_back(strs[i]);
} else {
hash[_strs[i]] = i;
}
}
return ret;
}
//------------------------------------------//
vector<string> anagrams(vector<string> &strs) {
map<string, pair<string, bool> > hash;
vector<string> res;
int i = 0;
while (i != strs.size()) {
string tmp = strs[i];
sort(tmp.begin(),tmp.end());
if (hash.find(tmp) != hash.end()) {
map<string, pair<string, bool> >::iterator it = hash.find(tmp);
if (!it->second.second) {
res.push_back(it->second.first);
it->second.second = true;
}
res.push_back(strs[i]);
} else {
pair<string, bool> p(strs[i], false);
hash.insert(pair<string, pair<string, bool> >(tmp, p));
}
++i;
}
return res;
}
};