-
Notifications
You must be signed in to change notification settings - Fork 0
/
Anagrams.cpp
42 lines (34 loc) · 1.15 KB
/
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
/*
Given an array of strings, return all groups of strings that are anagrams.
Link: http://www.lintcode.com/en/problem/anagrams/
Example:
Given ["lint", "intl", "inlt", "code"], return ["lint", "inlt", "intl"].
Given ["ab", "ba", "cd", "dc", "e"], return ["ab", "ba", "cd", "dc"].
Solution: We sort each string, to get the same key, then use a table to know whether this is a
anagram string or not.
Source: http://www.lintcode.com/en/problem/anagrams/
*/
class Solution {
public:
/**
* @param strs: A list of strings
* @return: A list of strings
*/
vector<string> anagrams(vector<string> &strs) {
// write your code here
unordered_map<string, int> table;
for (auto str : strs) {
sort(str.begin(), str.end());
++table[str];
}
vector<string> anagrams;
for (const auto& str : strs) {
string sorted_str(str); // copy this string
sort(sorted_str.begin(), sorted_str.end());
if (table[sorted_str] >= 2) {
anagrams.emplace_back(str);
}
}
return anagrams;
}
};