Showing posts with label How to determine if String has all unique characters. Show all posts
Showing posts with label How to determine if String has all unique characters. Show all posts

Wednesday, 23 September 2015

How to determine if String has all unique characters



It is a most basic question asked in interviews to check if string contains all unique characters or not.
Below sample program is a basic solution to this problem.

 /**  
  *   
  */  
 /**  
  * Program to determine if a string has all unique characters.  
  *   
  * @author Dixit  
  *   
  */  
 public class StringUniqueCharacters {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           String firstString = "America";  
           String secondString = "India";  
           String thridString = "Italy";  
           System.out  
                     .println("Result:" + isUniqueChars(firstString.toLowerCase()));  
           System.out.println("Result:"  
                     + isUniqueChars(secondString.toLowerCase()));  
           System.out  
                     .println("Result:" + isUniqueChars(thridString.toLowerCase()));  
      }  
      public static boolean isUniqueChars(String str) {  
           //Initialise a boolean array  
           boolean[] char_set = new boolean[256];  
           for (int i = 0; i < str.length(); i++) {  
                //get ASCII value of characters  
                int val = str.charAt(i);  
                //Check in the boolean array if it is unique then set the value to true at corresponding index position  
                //if value is already set at the required index position then return false  
                if (char_set[val])  
                     return false;  
                char_set[val] = true;  
           }  
           return true;  
      }  
 }  



Enjoy Programming.