Making Anagrams

Alice is taking a cryptography class and finding anagrams to be very useful. We consider two strings to be anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency For example, bacdc and dcbac are anagrams, but bacdcand dcbad are not.

Alice decides on an encryption scheme involving two large strings where encryption is dependent on the minimum number of character deletions required to make the two strings anagrams. Can you help her find this number?

Given two strings,  and , that may or may not be of the same length, determine the minimum number of character deletions required to make  and  anagrams. Any characters can be deleted from either of the strings.

Input Format

The first line contains a single string, 
The second line contains a single string, .

Constraints

  • It is guaranteed that  and  consist of lowercase English letters.

Output Format

Print a single integer denoting the number of characters which must be deleted to make the two strings anagrams of each other.

Sample Input

cde
abc

Sample Output

4

Explanation

We delete the following characters from our two strings to turn them into anagrams of each other:

  1. Remove d and e from cde to get c.
  2. Remove a and b from abc to get c.

We had to delete  characters to make both strings anagrams, so we print  on a new line.

#include <bits/stdc++.h>

using namespace std;

int makingAnagrams(string s1, string s2){
    // Complete this function
    map<char,int> s1_map;
    map<char,int> s2_map;
    int len1 = s1.length();
    int len2 = s2.length();
    int count = 0;
   //初始化 
    for(int i = 0;i<len1;i++){
        s1_map[s1[i]]=0;
        s2_map[s1[i]]=0;
    }
    for(int i = 0;i<len2;i++){
        s1_map[s2[i]]=0;
        s2_map[s2[i]]=0;
    }
    //赋值
    for(int i = 0;i<len1;i++)
        s1_map[s1[i]]++;
    for(int i = 0;i<len2;i++)
        s2_map[s2[i]]++;
    
    //比较计算
    map<char,int>::iterator it;
    for(it = s1_map.begin();it!=s1_map.end();it++){
        int tmp = it->second - s2_map[it->first];
        if(tmp<0)
            tmp = -tmp;
        count += tmp;
    }
    return count;
}

int main() {
    string s1;
    cin >> s1;
    string s2;
    cin >> s2;
    int result = makingAnagrams(s1, s2);
    cout << result << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/lyf-sunicey/p/8483453.html