I need to check in Java if a word consists of unique letters (case insensitive). As straight solution is boring, I came up with:
What about using an int to store the bits corresponding to the index of the letter of the alpabhet? or maybe a long to be able to reach 64 distinct symbols.
long mask;
// already lower case
string = string.toLowerCase();
for (int i = 0; i < string.length(); ++i)
{
int index = 1 << string.charAt(i) - 'a';
if (mask & index == index)
return false;
mask |= index;
}
return true;
This should be < O(n) on average case, O(n) on worst. But I'm not sure how much performant bitwise operations are in Java..