Check if string contains all unique characters

Avi Patel :

// O(N) - without additional data structure...

private boolean isUniqueWithoutDS(String str){
    boolean value = true;

    int checker = 0;

    for (int i = 0; i < str.length(); i++) {
        int c = str.charAt(i) - 'a';
        System.out.println("checker is : " + checker);
        System.out.println("1<<c is " + (1<<c));   
        if((checker & (1 << c))>0){
            value = false;
            break;
        }
        checker = checker | 1<<c;
    }

    return value;
}

This is my code and works fine, I am not able to understand how it works for capital and small letters combined string. For example "Zizu" it works. For all small lettered string it works and I know how it works as well.

Andreas :

Well, the answer might depend on language, but in Java (JLS 15.19. Shift Operators):

If the promoted type of the left-hand operand is int, then only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.

So it is like you execute c = c & 0x1f, or c = c % 32, so both uppercase A and lower-case a becomes c value of 0, for the purpose of the << operator.

I'd assume that other languages may work similarly, for a 32-bit int type.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=310252&siteId=1