forked from pezy/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.h
31 lines (30 loc) · 887 Bytes
/
solution.h
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
#include <string>
using std::string;
#include <vector>
using std::vector;
#include <unordered_map>
using std::unordered_map;
#include <algorithm>
using std::sort;
class Solution {
public:
vector<string> anagrams(vector<string> &strs) {
unordered_map<string, vector<string>::iterator> cache;
vector<string> ret;
for (auto iter = strs.begin(); iter != strs.end(); ++iter) {
string tmp_str(*iter);
sort(tmp_str.begin(), tmp_str.end());
auto found = cache.find(tmp_str);
if (found == cache.end())
cache[tmp_str] = iter;
else {
ret.push_back(*iter);
if (found->second != strs.end()) {
ret.push_back(*found->second);
found->second = strs.end();
}
}
}
return ret;
}
};