您的位置:首页 > 其它

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

2017-10-30 08:55 239 查看
问题描述:

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: True
Explanation:
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: 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.


问题分析:

每次记录最后出现的字符是否为只有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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: