Monday, February 8, 2016

Algorithm: Write a function to detect if the string has the unique character

February 8, 2016

So excited to have chance to write code for a new algorithm. 

Write a function to detect if the string has the unique character. 
Read the blog


this blog provides good answers for the question of unique character:

Notice that this method doesn't allocate an array of booleans. Instead, it opts for a clever trick. Since there are only 26 different characters possible and there are 32 bits in an int, the solution creates an int variable where each bit of the variable corresponds to one of the characters in the string. Instead of reading and writing an array, the solution reads and writes the bits of the number.

Julia's comment: first blog about bit manipulation - surprising, after the reading, it is much easy to understand the code: 
Two bit operation: 
1<< val 
 |=  

It is always helpful to write a few of small function:

int toInt(char c)
{
    return c-'a'; 
}

int OneShiftLeftNbits(int val)
{
   return 1 << val;
}

int checkNthBit(int val)
{
     // ...
}


public static boolean isUniqueChars(String str) {
    if (str.length() > 256) { // NOTE: Are you sure this isn't 26?
        return false;
    }
    int checker = 0;
    for (int i = 0; i < str.length(); i++) {
        int val = str.charAt(i) - 'a';
        if ((checker & (1 << val)) > 0) return false;
        checker |= (1 << val);
    }
    return true;
}
http://javahungry.blogspot.com/2014/11/string-has-all-unique-characters-java-example.html

To be continued.

No comments:

Post a Comment