Easiest way of checking if a string consists of unique characters?

前端 未结 12 1738
慢半拍i
慢半拍i 2021-01-04 23:34

I need to check in Java if a word consists of unique letters (case insensitive). As straight solution is boring, I came up with:

  1. For every char in a string che
12条回答
  •  借酒劲吻你
    2021-01-05 00:19

    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;
    }
    

提交回复
热议问题