Friday, 30 January 2015

Check if a String is made up of unique characters

//only for lower case letters between a-z , bit vector method
    public static boolean isUniqueChars(String str)
   
    {
        int length =  str.length();
       
        //for ASCII string
        if(length > 128)
        {
            return false;
        }
       
        int checker = 0 ; // bit vector
       
        for(int i = 0 ; i < length ; ++i)
        {
            int val = str.charAt(i) - 'a';
            if( ( checker & ( 1 << val ) ) > 0 ) return false ; // check if the character's bit position in bit vector is already 'on'
            checker |= ( 1 << val ); // turn the bit on for character's position
        }
       
        return  true ;
       
    }
   

No comments:

Post a Comment