I have troubles understanding this code that detects duplicates in string.
int checker = 0;
for(char ch : seed.toCharArray()){
int val = ch - 'a';
System.out.println(val);
if ((checker & (1 << val)) > 0){
// duplicate found
break;
}
checker |= (1 << val);
}
can someone explain me with an example how this works ?
Ok, say for example
ch = 'c':then evaluate the
ifcondition:means “shift 1 two places to the left”, which gives us binary 100, or decimal 4.
means “bit-wise and” between checker, ie check if that particular bit is already set.
if the bit was set, we are done, otherwise we perform
which means “c = c | 4”, which is a bit-wise or that will set the bit corresponding to ‘c’ to 1.