Run Code
|
API
|
Code Wall
|
Users
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Get all anagrams from given words
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
//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); }
g++
Show compiler warnings
[
+
] Compiler args
[
+
]
Show input
Compilation time: 0.61 sec, absolute running time: 0.14 sec, cpu time: 0 sec, memory peak: 3 Mb, absolute service time: 1.75 sec
fork mode
|
history
|
discussion
amazon zonama zomana ammazon zonnama anmanoz true