LeetCode之1-bit and 2-bit Characters(Kotlin)

问题:
We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11).

Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero.

Note:
1 <= len(bits) <= 1000.
bits[i] is always 0 or 1.


方法:
遍历数组,如果当前bit为0则指针移动一位,因为0必为first character;如果当前bit为1则指针移动两位,因为1X必为second character。当遍历到数组尾端时,如果指针正好等于数组最后一个元素的下标,则返回true;否则,数组尾端必为10,返回false。

具体实现:

class IsOneBitCharacter {
    fun isOneBitCharacter(bits: IntArray): Boolean {
        var i = 0
        while (i <= bits.lastIndex - 1) {
            if (bits[i] == 0) {
                i++
            } else if (bits[i] == 1) {
                i += 2
            }
        }
        if (i == bits.lastIndex) {
            return true
        }
        return false
    }
}

fun main(args: Array) {
    val array = intArrayOf(0, 0, 0, 0)
    val isOneBitCharacter = IsOneBitCharacter()
    val result = isOneBitCharacter.isOneBitCharacter(array)
    println("result: $result")
}

有问题随时沟通

具体代码实现可以参考Github

你可能感兴趣的:(LeetCode之1-bit and 2-bit Characters(Kotlin))