ISourceCode

Make the frequent cases fast and the rare case correct

C# – LINQ – Check if two strings are Anagrams using Dictionary data structure

Below is code written in C# and LINQ to check if two strings are anagram of each other using the .NET Dictionary class which is a hash table.

Ordering the dictionary according to the key in order to do a SequenceEqual might not be elegant since a dictionary is meant to be unordered ( take a look at the dump).

Execute it using Linqpad.

static void Main()
{
    string str1 = "ab# wrr2b";
    string str2 = "b#rba2 rw";

    Dictionary<char, int> dict1, dict2 = new Dictionary<char, int>();

    dict1 = StringDictionary(str1);
    dict2 = StringDictionary(str2);

    if (dict1.OrderBy(d => d.Key).SequenceEqual(dict2.OrderBy(d => d.Key)))
    {
        Console.WriteLine("True");
    }
    else Console.WriteLine("False");
}

public static Dictionary<char, int> StringDictionary(string str)
{
    return str.GroupBy(s => s).ToDictionary(d => d.Key, d => d.Count()).Dump();
}

OUTPUT:

anagramcheck

Alternatively SortedDictionary class can also be used

static void Main(string[] args)
{
	string str1 = "ab# wrr2b";
	string str2 = "b#rba2 r";

	SortedDictionary<char, int> dict1, dict2 = new SortedDictionary<char, int>();

	dict1 = StringDictionary(str1);

	dict2 = StringDictionary(str2);

	if (dict1.SequenceEqual(dict2))
	{
		Console.WriteLine("True");
	}
	else Console.WriteLine("False");

	Console.ReadKey();
}

public static SortedDictionary<char, int> StringDictionary(string str)
{
	return new SortedDictionary<char, int>(str.GroupBy(s => s).ToDictionary(d => d.Key, d => d.Count()));
}

Couple of years ago i wrote an article about the same algorithm and coded in C++ and Java.

    class Program
    {
        static void Main(string[] args)
        {
            string one = "hello";
            string two = "hellol";

            char[] first = one.ToCharArray();
            char[] second = two.ToCharArray();

            Dictionary<char, int> string1 = new Dictionary<char, int>();
            Dictionary<char, int> string2 = new Dictionary<char, int>();

            int count = 0;

            foreach (var x in first)
            {
                if (string1.ContainsKey(x))
                {
                    string1[x] = string1[x] + 1;
                }
                else
                {
                    string1.Add(x, count+1);
                }
                
            }

            count = 0;

            foreach (var x in second)
            {
                if (string2.ContainsKey(x))
                {
                    string2[x] = string2[x] + 1;
                }
                else
                {
                    string2.Add(x, count + 1);
                }

            }

            foreach (var kvp in string1)
            {
                Console.WriteLine(kvp.Key + " " + kvp.Value);
            }

            foreach (var kvp in string2)
            {
                Console.WriteLine(kvp.Key + " " + kvp.Value);
            }

            //if (string1.OrderBy(d => d.Key).SequenceEqual(string2.OrderBy(d => d.Key)))
            //{
            //    Console.WriteLine("True");
            //}
            //else Console.WriteLine("False");

            foreach (var kvp in string1)
            {
                if (!string2.ContainsKey(kvp.Key))
                {
                    Console.WriteLine("Not anagram");
                }

                if (string2.ContainsKey(kvp.Key))
                {
                    if (kvp.Value != string2[kvp.Key])
                    {
                        Console.WriteLine("No, Not an Anagram");
                    }
                }
            }

            Console.ReadKey();
        }
    }

One response to “C# – LINQ – Check if two strings are Anagrams using Dictionary data structure

  1. Pingback: Program to find if a string is an anagram of another string ( implemented in C++ and Java) « Source CO-De-tachment 2702

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: