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

前端 未结 12 1742
慢半拍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:13

    I would suggest a variant of (2) - use an array of "character already seen" flags instead of a hashset. As you loop through the string, exit immediately if the current character was already seen.

    If you have a bitvector class available (I forget whether Java provides one), you could use that, though the memory saving will not necessarily result in any speed improvement and could easily slow things down.

    It's O(n) worst case, though, and could have far better average performance depending on your strings - you may well find that most have a repeat near the start. In fact, strictly speaking, it's O(1) worst case anyway since a string longer than the size of the character set must have repeated characters so you have a constant bound to the number of characters you need to check in each string.

提交回复
热议问题