Tuesday, June 9, 2015

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

//Implement an algorithm to determine if a string has all unique characters.  
// This code has O(n^2) time complexity. [We can find a better solution]

public class UniqueChar{
public static void main(String args[])
{
UniqueChar uc = new UniqueChar();

System.out.println("Ashish : " + uc.detUnique("Ashish"));
System.out.println("Vishal : " + uc.detUnique("Vishal"));
System.out.println("Vinod : " + uc.detUnique("Vinod"));
System.out.println("Priyanka : " + uc.detUnique("Priyanka"));

}

public boolean detUnique(String string)
{
char charArray[]= string.toCharArray();
int count = 0;

for(char c : charArray)
{
count = 0;
for(char d : charArray)
if(d==c)
count++;

if(count>1)
return false;
}

return true;
}
}

____________________________________________________________

THE BETTER SOLUTION

//Implement an algorithm to determine if a string has all unique characters.
//The time complexity of this code is O(n), where n is the length of the string.
//The space complexity is O(1)

public class UniqueChar2
{
   public static void main(String args[])
   {
      UniqueChar2 obj = new UniqueChar2();
      System.out.println(obj.isUniqueChar("@n@rchy"));
   }

   public boolean isUniqueChar(String str)
   {
      if(str.length()>256) return false;

       boolean char_set[] = new boolean[256];
       for(int i=0;i<str.length();i++)
       {
          int val = str.charAt(i);
         if(char_set[val]) //Already found this char in string
            return false;

         char_set[val] = true;
       }

return true;
   }
}

No comments:

Post a Comment