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

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

    Option 2 is the best of the three - Hashing is faster than searching.

    However, there's an even faster method, if you have enough memory for it.

    Take advantage of the fact that a character set is limited and already enumerated, and keep track of what's appeared and what hasn't as you check each character.

    For example, if you're using one-byte chars, there are only 256 possibilities. You would only need 256 bits to keep track as you read through the string. If the character 0x00 occurs, flip the first bit. If the character 0x05 occurs, flip the sixth bit, and so on. When an already-flipped bit is encountered, the string isn't unique.

    It's worst case O(min(n, m)) where n is the length of the string, and m is the size of the character set.

    And of course, as I saw in another person's comment, if n > m (i.e. length of string > size of character set), then by pigeon-hole principle, there is a repeated character, determinable in O(1) time.

提交回复
热议问题