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

前端 未结 12 1827
野性不改
野性不改 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:18

    Just in case if anyone is looking for kotlin equivalent of unique characters in a string using bit vector

    fun isUnique(str: String): Boolean {
        var checker = 0
        for (i in str.indices) {
            val bit = str.get(i) - 'a'
            if (checker.and(1 shl bit) > 0) return false
            checker = checker.or(1 shl bit)
        }
        return true
    }
    

    Ref: https://www.programiz.com/kotlin-programming/bitwise

提交回复
热议问题