I need to check in Java if a word consists of unique letters (case insensitive). As straight solution is boring, I came up with:
I like the HashSet idea. It's conceptually simple, and only does one pass through the string. For a simple performance improvement, check the add return value. One thing you should be aware of is that this works by case-folding. in one direction. You could create a wrapper class around Character with different equals semantics to really be case-insensitive.
Interestingly, Apache Commons has a CaseInsensitiveMap (src) which works by upper-casing then lower-casing the key. As you probably know, Java's HashSet is backed by a HashMap.
public static boolean allUnique(String s)
{
// This initial capacity can be tuned.
HashSet hs = new HashSet(s.length());
for(int i = 0; i < s.length(); i++)
{
if(!hs.add(s.charAt(i).toUpperCase())
return false;
}
return true;
}