Given two strings as an input for a function, return true if one string is a permutation of another

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string str1 = "aabbcdeffaa";
            string str2 = "fabafbcadae";
            Console.WriteLine(IsPermutation(str1, str2));
        }

        public static bool IsPermutation(string str1, string str2)
        {
            if (str1 != null && str2 != null && str1.Length == str2.Length)
            {
                Hashtable ht = new Hashtable();
                for (int i = 0; i < str1.Length; i++)
                {
                    if (ht.Contains(str1[i]))
                    {
                        ht[str1[i]] = int.Parse(ht[str1[i]].ToString()) + 1;
                    }
                    else
                    {
                        ht.Add(str1[i], 1);
                    }
                }
                for (int i = 0; i < str2.Length; i++)
                {
                    if (ht.Contains(str2[i]) && int.Parse(ht[str2[i]].ToString()) != 0)
                    {
                        ht[str2[i]] = int.Parse(ht[str2[i]].ToString()) - 1;
                    }
                    else
                    {
                        return false;
                    }
                }
                return true;
            }
            return false;
        }
    }
}

Output
======
True
Press any key to continue . . .
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

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