717. 1-bit and 2-bit Characters(第九周)

来源:互联网 发布:电脑软件开发学校 编辑:程序博客网 时间:2024/06/05 07:34

Description

1-bit and 2-bit Characters - LeetCode

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: TrueExplanation: 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: FalseExplanation: The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character.

Solution

看题目可以得出一个规律,那就是只要碰到1的bit,我们就可以认为这个bit和下一个bit组成一个2-bit字符,如果碰到的是0,那么就可以知道这个字符是1-bit字符。

根据这条规律,我们只需要从前往后遍历整个数组,判断最后得到的flag的值就是要返回的值。

代码如下:

code

submission

class Solution {public:    bool isOneBitCharacter(vector<int>& bits) {        int i = 0;        bool flag = 0;        while (i < bits.size())        {            if (bits[i] == 1) {                i += 2;                flag = 0;            }            else {                i += 1;                flag = 1;            }        }        return flag;    }};
原创粉丝点击