问题描述:
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;
}
};