Making Anagrams

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 bacdc and dcbad are not.

Alice is taking a cryptography class and finding anagrams to be very useful. She 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, s1 and s2, that may not be of the same length, determine the minimum number of character deletions required to make s1 and s2 anagrams. Any characters can be deleted from either of the strings.


Example:

Input:  s1="cde", s2="abc"
Output: 4

Approach

Java


public class MakingAnagrams {
    public static void main(String[] args) {
        String s1 = "cde";
        String s2 = "abc";

        int result = makingAnagrams(s1, s2);
        System.out.println(result);
    }

    private static int makingAnagrams(String s1String s2) {

        int f1[] = new int[26];
        for (int i = 0; i < s1.length(); i++) {
            f1[s1.charAt(i) - 'a']++;
        }
        for (int i = 0; i < s2.length(); i++) {
            f1[s2.charAt(i) - 'a']--;
        }
        int sum = 0;
        for (int i = 0; i < 26; i++) {
            sum += Math.abs(f1[i]);
        }
        return sum;
    }
}


C++

#include <bits/stdc++.h>
using namespace std;

int makingAnagrams(string s1string s2)
{
    int f1[26] = {0};
    for (int i = 0i < s1.size(); i++)
    {
        f1[s1[i] - 'a']++;
    }
    for (int i = 0i < s2.size(); i++)
    {
        f1[s2[i] - 'a']--;
    }
    int sum = 0;
    for (int i = 0i < 26i++)
    {
        sum += abs(f1[i]);
    }
    return sum;
}

int main()
{

    string s1 = "cde";
    string s2 = "abc";

    int result = makingAnagrams(s1s2);
    cout << result << "\n";

    return 0;
}


No comments:

Post a Comment