Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character in C++

C++Server Side ProgrammingProgramming

Suppose we have two strings of equal length, we have to find a minimum number of alterations required to make two strings anagram, without deleting any character. The Anagram is two strings that have the same set of characters. Suppose two strings are “HELLO”, and “WORLD” here number of required changes is 3, as three characters are different in this case.

The idea is simple, we have to find the frequency of each character in the first string, then go through the second string, if characters in the second string are present, in the frequency array, then decrease the frequency value. If the frequency value is less than 0, then increase the final count by 1.

Example

 Live Demo

#include <iostream>
using namespace std;
int countAlteration(string str1, string str2) {
   int count = 0;
   int frequency[26];
   for (int i = 0; i < 26; i++){
      frequency[i] = 0;
   }
   for (int i = 0; i < str1.length(); i++)
   frequency[str1[i] - 'A']++;
   for (int i = 0; i < str2.length(); i++){
      frequency[str2[i] - 'A']--;
      if (frequency[str2[i] - 'A'] < 0)
      count++;
   }
   return count;
}
int main() {
   string s1 = "HELLO", s2 = "WORLD";
   cout << "Number of required alteration: " << countAlteration(s1, s2);
}

Output

Number of required alteration: 3
raja
Published on 21-Oct-2019 07:27:27
Advertisements