The problem is to figure out if there aren’t any duplicate characters in a given string. The constraints are that the string only contains characters a-z (lower case only).
The obvious solution is to use an array (or hash table) to keep track of characters you have encountered. But the problem is you aren’t allowed to use data structures.
Following is one solution to the problem. But I don’t quite understand how it’s working. I can see that it’s using the bits of an integer to keep track of characters encountered.
public boolean isUniqueChars(String str) {
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;
}
You’re correct in that it sets bits for each letter. But it checks first (using bitwise and), and if it has already found the current letter then it knows that the string does not contain unique letters.