1-bit and 2-bit Characters问题及解法

来源:互联网 发布:php mysql 扩展 编辑:程序博客网 时间:2024/06/05 08:42

问题描述:

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.

示例:

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

问题分析:

每次记录最后出现的字符是否为只有0构成的,最终返回记录标识即可。


过程详见代码:

class Solution {public:    bool isOneBitCharacter(vector<int>& bits) {        bool res = 0;for (int i = 0; i < bits.size();){if (!bits[i]){i++;res = 1;}else{i += 2;res = 0;}}return res;    }};


原创粉丝点击