We have two special characters. The first character can be represented by one bit0. The second character can be represented by two bits (10or11).

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.

这道题的思路是从index = 0开始,如果当前的bit为0,index自增1,如果当前的bit为1,index自增2。最后如果index停在最后一个数字上,加之最后一个数字保证是0,则最后的0必然是1 bit字符,如果index越过了最后一个数字,则最后一个0一定是和前一个1组成10的2 bit字符。

有一个小陷阱,可能一看到这个题,就容易去考虑这样的一个字符串到底有多少种decode的方法,然而根据给定的条件,只可能有一种decode方法

class Solution {
    public boolean isOneBitCharacter(int[] bits) {
        if(bits == null || bits.length == 0)
            return false;
        if(bits.length == 1)
            return bits[0] == 0;

        int i = 0;
        while(i < bits.length - 1) {
            if(bits[i] == 0)
                i += 1;
            else
                i += 2;
        }

        return i == bits.length - 1;
    }
}

leetcode答案里的另一种思路,找到倒数第二个0,然后统计这两个0之间有几个1,如果1的个数为偶数则最后一个0是1bit字符。倒数第二0,不管是单独的0还是10中的0,都是合理的,因此可以从倒数第二个0开始数有多少1

class Solution {
    public boolean isOneBitCharacter(int[] bits) {
        if(bits.length == 1)
            return bits[0] == 0;

        int i = bits.length - 2;
        while(i >= 0 && bits[i] == 1)
            i--;

        int count = bits.length - 2 - (i + 1) + 1;
        return count % 2 == 0;
    }
}

results matching ""

    No results matching ""