Thursday, August 2, 2018

Strings: Making Anagrams

Question :- Print a single integer denoting the number of characters you must delete to make the two strings anagrams of each other.

Sample Input :- 
cde
abc

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 must delete  characters to make both strings anagrams, so we print  on a new line.
Answer:- 
static int makeAnagram(string a, string b) 
        {
            var aChar = a.ToLower().ToCharArray();
            var bChar = b.ToLower().ToCharArray();
            Array.Sort(aChar);
            Array.Sort(bChar);
            var newAChar = new Dictionary<char, int>();
            var newAcharIndex = 0;

            var newBChar = new Dictionary<char, int>();
            var newBcharIndex = 0;
            int count = 0;       
            for (int i = 0; i < aChar.Length; i++)
            {
                if (bChar.Contains(aChar[i]))
                {
                    if (!newAChar.ContainsKey(aChar[i]))
                        newAChar.Add(aChar[i], 1);
                    else
                        newAChar[aChar[i]]++;
                }
                else
                    count++;
            }
            for (int i = 0; i < bChar.Length; i++)
            {
                if (aChar.Contains(bChar[i]))
                {
                    if (!newBChar.ContainsKey(bChar[i]))
                        newBChar.Add(bChar[i], 1);
                    else
                        newBChar[bChar[i]]++;
                }
                else
                    count++;
            }

            foreach (var key in newAChar.Keys)
            {
                if (newAChar[key] != newBChar[key])
                    count += Math.Abs(newAChar[key] - newBChar[key]);
            } 
           return count;       
        }









No comments:

Post a Comment

Kafka setup in window

Here's a step-by-step guide on how to do it : 1. Prerequisites : Before you begin, make sure you have the following prerequisites inst...