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指針

相關文章
相關標籤/搜索