Algorithm to find a string contains unique characters or not: C#

Algorithm to find a string contains unique characters or not:

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the String");
            string inp = Console.ReadLine();
            bool result = CheckUniq(inp);
            if (!result)
                Console.WriteLine("The input string contains duplicate characters");
            else Console.WriteLine("No duplicates");
        }

        static bool CheckUniq(string input)
        {

            //take a bool array of size 256 considering the ASCII
            bool[] char_set = new bool[256];
            for(int i=0;i<input.Length;i++)
            {
                int val = input[i];
                if (char_set[val]) return false;
                char_set[val] = true;
            }
            return true;
        }
    }


We can also sort the string and check whether the adjacent characters are equal or not. But as usual, sorting algorithms consume more time.  

Comments

Popular posts from this blog

Base 64 encoding and decoding

LINQ Queries with GROUP BY, INNER JOIN, COUNT and SUM: Examples

How to write Custom delete Confirmation Modal for Kendo Grid in MVC: