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':
int val = 'c' - 'a' = 2; //The char value for 'c' is two greater that that for 'a'
then evaluate the if condition:
1 << 2
means "shift 1 two places to the left", which gives us binary 100, or decimal 4.
checker & 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
c |= 4
which means "c = c | 4", which is a bit-wise or that will set the bit corresponding to 'c' to 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With