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
|
/*
Challenge 094
TASK #1 � Group Anagrams
Submitted by: Mohammad S Anwar
You are given an array of strings @S.
Write a script to group Anagrams together in any random order.
An Anagram is a word or phrase formed by rearranging the letters of a
different word or phrase, typically using all the original letters exactly
once.
Example 1:
Input: ("opt", "bat", "saw", "tab", "pot", "top", "was")
Output: [ ("bat", "tab"),
("saw", "was"),
("top", "pot", "opt") ]
Example 2:
Input: ("x")
Output: [ ("x") ]
*/
#include <algorithm>
#include <iostream>
#include <list>
#include <map>
#include <string>
std::string make_key(const std::string& str) {
std::string out{ str };
std::sort(out.begin(), out.end());
return out;
}
int main(int argc, char* argv[]) {
std::map<std::string, std::list<std::string>> map; // maps keys to lists of words
for (int i = 1; i < argc; i++) {
auto key = make_key(argv[i]);
auto found = map.find(key);
if (found == map.end()) { // not found, create new item
std::list<std::string> list;
list.push_back(argv[i]);
map[key] = list;
}
else { // append to existing item
found->second.push_back(argv[i]);
}
}
std::cout << "[ ";
bool first1 = true;
for (auto& it1 : map) {
if (!first1)
std::cout << "," << std::endl << " ";
first1 = false;
std::cout << "(";
bool first2 = true;
for (auto& it2 : it1.second) {
if (!first2)
std::cout << ", ";
first2 = false;
std::cout << "\"" << it2 << "\"";
}
std::cout << ")";
}
std::cout << " ]" << std::endl;
}
|