Explain the use of a bit vector for determining if all characters are unique

前端 未结 12 1808
野性不改
野性不改 2020-12-04 04:23

I am confused about how a bit vector would work to do this (not too familiar with bit vectors). Here is the code given. Could someone please walk me through this?

         


        
12条回答
  •  时光取名叫无心
    2020-12-04 05:00

    Lets break down the code line by line.

    int checker = 0; We are initiating a checker which will help us find duplicate values.

    int val = str.charAt(i) - 'a'; We are getting the ASCII value of the character at the 'i'th position of the string and subtracting it with the ASCII value of 'a'. Since the assumption is that the string is lower characters only, the number of characters in limited to 26. Hece, the value of 'val' will always be >= 0.

    if ((checker & (1 << val)) > 0) return false;

    checker |= (1 << val);

    Now this is the tricky part. Lets us consider an example with string "abcda". This should ideally return false.

    For loop iteration 1:

    Checker: 00000000000000000000000000000000

    val: 97-97 = 0

    1 << 0: 00000000000000000000000000000001

    checker & (1 << val): 00000000000000000000000000000000 is not > 0

    Hence checker: 00000000000000000000000000000001

    For loop iteration 2:

    Checker: 00000000000000000000000000000001

    val: 98-97 = 1

    1 << 0: 00000000000000000000000000000010

    checker & (1 << val): 00000000000000000000000000000000 is not > 0

    Hence checker: 00000000000000000000000000000011

    For loop iteration 3:

    Checker: 00000000000000000000000000000011

    val: 99-97 = 0

    1 << 0: 00000000000000000000000000000100

    checker & (1 << val): 00000000000000000000000000000000 is not > 0

    Hence checker: 00000000000000000000000000000111

    For loop iteration 4:

    Checker: 00000000000000000000000000000111

    val: 100-97 = 0

    1 << 0: 00000000000000000000000000001000

    checker & (1 << val): 00000000000000000000000000000000 is not > 0

    Hence checker: 00000000000000000000000000001111

    For loop iteration 5:

    Checker: 00000000000000000000000000001111

    val: 97-97 = 0

    1 << 0: 00000000000000000000000000000001

    checker & (1 << val): 00000000000000000000000000000001 is > 0

    Hence return false.

提交回复
热议问题