Check pairs of phrases for anagrams by counting letters (ignoring case and spaces) in an array of 26 counters.
Solution
main.cpp
#include <array>
#include <cctype>
#include <iostream>
#include <string>
bool anagrams(const std::string& a, const std::string& b) {
std::array<int, 26> count{};
for (unsigned char c : a) if (std::isalpha(c)) ++count[std::tolower(c) - 'a'];
for (unsigned char c : b) if (std::isalpha(c)) --count[std::tolower(c) - 'a'];
for (int n : count) if (n != 0) return false;
return true;
}
int main() {
std::cout << anagrams("Listen", "Silent") << anagrams("Dormitory", "Dirty room")
<< anagrams("Hello", "World") << anagrams("Astronomer", "Moon starer") << '\n';
return 0;
}
Output Verified by compiling and running
1101
Add one for each letter of the first phrase and subtract one for each letter of the second; anagrams leave every counter at zero. O(n) time, unlike the O(n log n) sorting approach.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!