Find Duplicates in String using bitwise operator

I should be mindful of taking bits. For example if I want to cover all 128 ASCII codes in string then I need 128 bit datatype and long has only 8 bytes (8 bytes * 8 bits) = 64 bits. Hence this method works well if I have string with alphabets only.

Let's assume my string contains only small letters. So I just need 26 bits for all 26 letters. 

class DuplicatesInString {
    // Asumption : All characters are 'a' to 'z'
    static void printDuplicates(String str) {
        int resultBits = 0;
        for(int i = 0; i < str.length(); i++) {
            int tempShiftBits = 1; // Assign a byte ; 00000000 00000000 00000000 00000001
            // If character is 'd'. ASCII code of 'd' = 100 and shiftCount = 3
            int shiftCount = str.charAt(i) - 97;
            tempShiftBits = tempShiftBits << shiftCount; // 00000000 00000000 00000000 00001000
            if((resultBits & tempShiftBits) > 0) {
                System.out.println(str.charAt(i) + " is duplicate. ");
            } else {
                resultBits = resultBits | tempShiftBits;
            }
        }
    }
public static void main (String[] args) {
String str = "finding";
        printDuplicates(str);
}
}

Comments

Popular posts from this blog

SQL basic interview question

gsutil Vs Storage Transfer Service Vs Transfer Appliance