LearnFrenzy
Sign in Take a free test

std::string · String Programs · Question 4

Check whether two strings are anagrams in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links