Implement an algorithm to determine if a string has all unique characters.

 

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Text;

   5:  

   6: namespace IsUniqueCharacters

   7: {

   8:     class Program

   9:     {

  10:         private static bool isUniqueChars(string str)

  11:         {          

  12:  

  13:             bool[] arrBool = new bool[256];

  14:  

  15:             for (int i = 0; i < str.Length; i++)

  16:             {

  17:                 int val = str[i];

  18:                 if (arrBool[val])

  19:                     return false;

  20:  

  21:                 arrBool[val] = true;

  22:             }

  23:  

  24:             return true;

  25:         }

  26:  

  27:         private static void FindUniqueChars(string str)

  28:         {

  29:             if (!isUniqueChars(str))

  30:             {

  31:                 Console.WriteLine("No unique string");

  32:             }

  33:  

  34:             int[] arrIndex = new int[256];

  35:             for (int i = 0; i < str.Length; i++)

  36:             {

  37:                 arrIndex[str[i]]++;

  38:             }

  39:  

  40:             Console.Write("Duplicate chars in ({0}) = ", str);

  41:             for (int j = 0; j < 256; j++)

  42:             {

  43:                 if (arrIndex[j] > 1)

  44:                     Console.Write("{0} ", (char)j);

  45:             }

  46:             Console.WriteLine();

  47:         }

  48:  

  49:  

  50:         static void Main(string[] args)

  51:         {

  52:             string[] arrStrings = new string[] { "abcdedisp", "akcidiugs", "sacddes", "abcsnil", "abckiipdnsu", "iiiiiiii", "aaaiiimmm" };

  53:  

  54:             foreach (string str in arrStrings)

  55:             {

  56:                 if (isUniqueChars(str))

  57:                     Console.WriteLine("{0} is Uniq", str);

  58:                 else

  59:                     Console.WriteLine("{0} is NOT Uniq", str);

  60:  

  61:                 FindUniqueChars(str);

  62:  

  63:             }

  64:  

  65:             Console.ReadKey();

  66:         }

  67:     }

  68: }

Advertisements