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).git

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.github

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。bash

具体实现:ui

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<String>) {
    val array = intArrayOf(0, 0, 0, 0)
    val isOneBitCharacter = IsOneBitCharacter()
    val result = isOneBitCharacter.isOneBitCharacter(array)
    println("result: $result")
}
复制代码

有问题随时沟通spa

具体代码实现能够参考Github指针

相关文章
相关标签/搜索