I know this question has been asked before now but in Python. Recently, I set out to write an anagram in C#. For instance, orchestra can be rearranged into carthorse and the anagram should not have more repeated than the original. The function is meant to check if the two words are the same and return true in this case. I started with putting the two words in two separate dictionaries with the letters as a key and the count as value.
The idea is using a dictionary ensures the keys can not be repeated. Then I looped through the second dictionary (secondString
) and checked if each letter existed as a key in the first dictionary (firstString
). Additionally, if the letter existed, the code checks if they have the same count. The rest of the code is self-explanatory.
using System;
using System.Collections.Generic;
public class AreAnagrams
{
public static bool AreStringsAnagrams(string a, string b)
{
Dictionary<char,int> firstString = new Dictionary<char,int>();
Dictionary<char,int> secondString = new Dictionary<char,int>();
foreach(char character in a)
{
if(firstString.ContainsKey(character)== true)
{
firstString[character]+=1;
}
else
firstString[character]=1;
}
foreach(char character2 in b)
{
if(secondString.ContainsKey(character2)== true)
{
secondString[character2]+=1;
}
else
secondString[character2]=1;
}
foreach(KeyValuePair<char,int> letterValue in secondString)
{
if(firstString.ContainsKey(letterValue.Key))
{
if(firstString[letterValue.Key] != secondString[letterValue.Key]){
return false;
}
}
else
{
return false;
}
}
//throw new NotImplementedException("Waiting to be implemented.");
return true;
}
public static void Main(string[] args)
{
Console.WriteLine(AreStringsAnagrams("momdad", "dadmom"));
}
}
But I scored 75% and I feel this can be improved on. Also, is there any easy conversion from string to dictionary?