Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Get all anagrams from given words
//Title of this code #include <iostream> #include <vector> #include <map> #include <string> #include <list> #include <set> using namespace std; /* - Go through on the words list and make a charMap for every word - check the charMaps equality and write out when we got a match */ map<char, int> getCharMap(const string& s) { map<char, int> m; for (int i = 0; i < s.length(); ++i) { if (m.find(s[i]) == m.end()) m[s[i]] = 1; else ++m[s[i]]; } return m; } bool areCharMapEqual(map<char, int>& m1, map<char, int>& m2) { if (m1.size() != m2.size()) return false; auto it1 = m1.begin(); auto it2 = m2.begin(); // the sizes are the same so we don't need further checking while (it1 != m1.end()) { if (it1->first != it2->first || it1->second != it2->second) return false; ++it1; ++it2; } return true; } struct StringWithCharMap { string str; map<char, int> strMap; StringWithCharMap(string s, map<char, int> m): str(s), strMap(m) {} }; void findAnagrams(vector<string>& words) { list<StringWithCharMap> wordsCharMaps; for (int i = 0; i < words.size(); ++i) wordsCharMaps.push_back( StringWithCharMap(words[i], getCharMap(words[i])) ); while (!wordsCharMaps.empty()) { map<char, int> curStrMap = wordsCharMaps.begin()->strMap; cout << wordsCharMaps.begin()->str << " "; wordsCharMaps.erase(wordsCharMaps.begin()); auto it = wordsCharMaps.begin(); while (!wordsCharMaps.empty() && it != wordsCharMaps.end()) { if (areCharMapEqual(curStrMap, it->strMap)) { cout << it->str << " "; it = wordsCharMaps.erase(it); } else ++it; } cout << endl; } } int main() { vector<string> words = {"amazon", "zonama", "zomana", "ammazon", "zonnama", "", "anmanoz"}; findAnagrams(words); map<char, int> m1 = getCharMap("zonama"); map<char, int> m2 = getCharMap("zomana"); cout << boolalpha << areCharMapEqual(m1, m2); }
run
|
edit
|
history
|
help
0
stl_sizeof.cc
a simple tuple implementation
Test 1(2021)
Longest Palindrom in String
random lotto number game
c2p
MyStack
SubprogramModificat
Hello world.c
tes