-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind_anagram.h
More file actions
43 lines (38 loc) · 1.17 KB
/
Copy pathfind_anagram.h
File metadata and controls
43 lines (38 loc) · 1.17 KB
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
#ifndef CPP_ALGORITHM_FIND_ANAGRAM_H
#define CPP_ALGORITHM_FIND_ANAGRAM_H
#include <algorithm>
#include <string>
#include <unordered_map>
#include <vector>
namespace FindAnagram
{
/**
* \brief Find the anagram mappings.
* \param dictionary the dictionary of words
* \return the anagram mappings
*/
std::vector<std::vector<std::string>> FindAnagramMappings(
const std::vector<std::string>& dictionary);
}
// ----------------------------------------------------------------------------
inline std::vector<std::vector<std::string>> FindAnagram::FindAnagramMappings(
const std::vector<std::string>& dictionary)
{
std::unordered_map<std::string, std::vector<std::string>> dictionary_map;
for (const std::string& word : dictionary)
{
std::string sorted_word = word;
std::ranges::sort(sorted_word);
dictionary_map[sorted_word].emplace_back(word);
}
std::vector<std::vector<std::string>> anagram_mappings;
for (const auto& [word, anagrams] : dictionary_map)
{
if (anagrams.size() > 1)
{
anagram_mappings.emplace_back(anagrams);
}
}
return anagram_mappings;
}
#endif