Detecting if a string has unique characters: comparing my solution to “Cracking the Coding Interview?”

后端 未结 7 1841
孤街浪徒
孤街浪徒 2020-12-22 16:43

I am working through the book \"Cracking the Coding Interview\" and I have come across questions here asking for answers, but I need help comparing my answer to the solution

7条回答
  •  死守一世寂寞
    2020-12-22 17:39

    Since a char value can hold one of only 256 different values, any string that's longer than 256 characters must contain at least one duplicate.

    The remainder of the code uses checker as a sequence of bits, with each bit representing one character. It seems to convert each character to an integer, starting with a = 1. It then checks the corresponding bit in checker. If it's set, it means that character has already been seen, and we therefore know that the string contains at least one duplicate character. If the character hasn't yet been seen, the code sets the corresponding bit in checker and continues.

    Specifically, (1< generates an integer with a single 1 bit in position val. For example, (1<<3) would be binary 1000, or 8. The expression checker & (1< will return zero if the bit in position val is not set (that is, has value 0) in checker, and (1<, which is always non-zero, if that bit is set. The expression checker |= (1< will set that bit in checker.

    However, the algorithm seems to be flawed: it doesn't seem to account for the uppercase characters and punctuation (which generally come before the lowercase ones lexicographically). It would also seem to require a 256-bit integer, which is not standard.

    As rolfl mentions in the comment below, I prefer your solution because it works. You can optimize it by returning false as soon as you identify a non-unique character.

提交回复
热议问题