How to count the characters need to be removed so that two strings become anagram in C++

1 Answer

0 votes
#include <iostream>

const int TotalABCLetters = 26;

int CountCharactersNeedToBeRemovedForAnagram(std::string str1, std::string str2) {
    int count1[TotalABCLetters] = { 0 }, count2[TotalABCLetters] = { 0 };
 
    // count char frequency str1
    for (int i = 0; str1[i] != '\0'; i++)
        count1[str1[i] - 'a']++;
 
    // count char frequency str2
    for (int i = 0; str2[i] != '\0'; i++)
        count2[str2[i] - 'a']++;
 
    int result = 0;
    for (int i = 0; i < TotalABCLetters; i++)
        result += abs(count1[i] - count2[i]);
    
    return result;
}
 
int main()
{
    std::string str1 = "masterfx", str2 = "ksampret";
    
    std::cout << CountCharactersNeedToBeRemovedForAnagram(str1, str2);
}




/*
run:

4

*/

 



answered Sep 26, 2022 by avibootz
edited Sep 27, 2022 by avibootz
...