How would I best implement a Java function which accepts a String parameter and returns true
or false
depending on whether the String is comprised of all different characters or not.
This is an interview question. The implementation should use bit masking to store the occurrence of characters and no other auxiliary data structures.
Note: the requirement to use bit masking makes this question different from:
As requested, here's my effort so far. Please re-open the question if possible now:
public static boolean hasAllUniqueCharactersUsingBitMasking(String string) {
final int length = string.length();
final int nBitsToStoreAllUnicodeCharacters =
(int) Math.ceil(Math.log(Character.MAX_CODE_POINT) / Math.log(2d));
BitSet bitSet = new BitSet(nBitsToStoreAllUnicodeCharacters);
for (int i = 0; i < length; i++) {
char c = string.charAt(i);
if (bitSet.get(c)) {
return false;
}
bitSet.set(c);
}
return true;
}