Question :- Print a single integer denoting the number of characters you must delete to make the two strings anagrams of each other.
Sample Input :-
Sample Input :-
cde
abc
Explanation
We delete the following characters from our two strings to turn them into anagrams of each other:
- Remove
d
ande
fromcde
to getc
. - Remove
a
andb
fromabc
to getc
.
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