美文网首页
[leetcode]717.1-bit and 2-bit Ch

[leetcode]717.1-bit and 2-bit Ch

作者: cherrycoca | 来源:发表于2017-12-22 16:48 被阅读0次

    1-bit and 2-bit Characters

    描述
    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.
    Example 1:

    Input:
    bits = [1, 0, 0]
    Output: True
    Explanation:
    The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character.

    Example 2:

    Input:
    bits = [1, 1, 1, 0]
    Output: False
    Explanation:
    The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character.

    Note:

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

    思路
    有两个数,一个用0表示,一个用10或11表示。判断给定字符串的最后一个数是否是一位的。
    分情况讨论,若字符串长度大于2则从头遍历,标准是遇0就到下一位,遇1则中间跳一位到下一位,如果恰好还剩两位且倒数第二位为0则true,否则false;如果还剩一位则必然为true。还剩下长度为2和1的情况分别写if-else讨论。

    问题
    一开始测试用例不通过是只考虑了大于2的情况,但是少考虑了剩下的情况。应该全面考虑问题的各种可能。
    感觉这样分情况讨论还是过于繁琐了点,应该有更简洁的办法。

    代码

    bool isOneBitCharacter(int* bits, int bitsSize) {
        int count=bitsSize;
        int i=0;
        if(count>2){
             for(;count>2;){
            if(bits[i]==0){
                i++;
                count--;
            }
            else{
                i=i+2;
                count=count-2;
            }
        }
        if(count==2){
            if(bits[bitsSize-2]==0)
            return true;
            else return false;
        }
        else
            return true;
        }
        else
            if(count==1){
                return true;
            }
            else
            if(bits[bitsSize-2]==0)
            return true;
            else return false;
    }
    

    相关文章

      网友评论

          本文标题:[leetcode]717.1-bit and 2-bit Ch

          本文链接:https://www.haomeiwen.com/subject/ihlxgxtx.html