Skip to content

Instantly share code, notes, and snippets.

@martin-minarik
Created June 12, 2024 00:15
Show Gist options
  • Save martin-minarik/eedce510bb03fb36df5513b79692d691 to your computer and use it in GitHub Desktop.
Save martin-minarik/eedce510bb03fb36df5513b79692d691 to your computer and use it in GitHub Desktop.
Anagram
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
bool is_anagram(const string &str_a, const string &str_b)
{
unordered_map<char, int> chars_occurrences;
if (str_a.length() != str_b.length())
return false;
for (const char &chr : str_a)
chars_occurrences[chr]++;
for (const char &chr : str_b)
chars_occurrences[chr]--;
return all_of(chars_occurrences.begin(),
chars_occurrences.end(),
[](const auto &item){ return item.second == 0; });
}
int main()
{
cout << boolalpha;
cout << is_anagram("dog", "god") << endl;
cout << is_anagram("dog", "fog") << endl;
cout << is_anagram("world", "owrld") << endl;
cout << is_anagram("world", "word") << endl;
cout << is_anagram("world", "wonderful") << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment