Anagram

Two strings are said to be anagrams, if one string can be obtained by rearranging the letters of another.

Examples:

  • dog, god
  • abac, baac
  • anagram, nagaram
  • silent, listen
class Anagram
    {
        public static void IsAnagram(string word1, string word2)
        {
            bool flag = true;
            if (word1.Length != word1.Length)
            {
                flag = false;
            }

            var aFrequency = CalculateFrequency(word1);
            var bFrequency = CalculateFrequency(word2);

            foreach (var key in aFrequency.Keys)
            {
                if (!bFrequency.ContainsKey(key)) flag = false;
                if (aFrequency[key] != bFrequency[key]) flag = false;
            }

            if (flag)
            {
                Console.WriteLine("Yes! Words \"{0}\" and \"{1}\" are Anagrams", word1, word2);
            }
            else
            {
                Console.WriteLine("No! Words \"{0}\" and \"{1}\" are not Anagrams", word1, word2);
            }
            Console.ReadLine();
        }
        public static Dictionary<char, int> CalculateFrequency(string input)
        {
            var frequency = new Dictionary<char, int>();
            foreach (var c in input)
            {
                if (!frequency.ContainsKey(c))
                {
                    frequency.Add(c, 0);
                }
                ++frequency[c];
            }
            return frequency;
        }
        static void Main(string[] args)
        {
            IsAnagram("silent", "listen");
        }
    }

Output:

Anagrams

Leave a Reply

Your email address will not be published. Required fields are marked *