How to make two strings anagram by removing characters in C++

1 Answer

0 votes
#include <iostream>
#include <algorithm>
 
const int TotalABCLetters = 26;

void RemoveByChar(std::string &s, char ch) {
    if (s.find(ch) != std::string::npos)
        s.erase(std::remove(s.begin(), s.end(), ch), s.end());
}
 
void RemoveCharactersNeedToBeRemovedForAnagram(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']++;
  
    for (int i = 0; i < TotalABCLetters; i++) {
        if (abs(count1[i] - count2[i])) {
            RemoveByChar(str1, (char)(i + 'a'));
            RemoveByChar(str2, (char)(i + 'a'));
        }
       
    }
}
  
int main()
{
    std::string str1 = "masterfx", str2 = "ksampret";
     
    RemoveCharactersNeedToBeRemovedForAnagram(str1, str2);
    
    std::cout << str1 << "\n";
    
    std::cout << str2 << "\n";
}
 



/*
run:
 
master
samret
 
*/

 



answered Sep 27, 2022 by avibootz

Related questions

1 answer 120 views
1 answer 123 views
1 answer 150 views
1 answer 151 views
1 answer 127 views
...