Monday, August 10, 2015

String has unique characters?

Problem Statement

Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?

Solution 1 - With additional data structures

 public boolean uniqueString1(String s)
 {
  HashMap map = new HashMap();
  for(int i=0; i< s.length(); i++)
  {
   if(map.get(s.charAt(i))== null)
   {
    map.put(s.charAt(i), true);
   }
   else return false;
  }
  return true;
 }


Solution 2 - Without additional data structures


 public boolean uniqueString2(String s)
 {
  if(s.length() > 256) return false;

  int checker=0, val;
  for(int i =0;i < s.length();i++)
  {
   val = s.charAt(i) - 'a';
   if((checker & (1 << val)) > 0) return false;
   checker |= (1 << val);
  }
  return true;
 }

Note: This is a problem from the book "Cracking the Coding Interview: 150 Programming Questions and Solutions", which I am currently reading.

No comments:

Post a Comment