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.
思路:若最后一位是1,则结果必为false;
若最后一位是0,只需要判断前边有多少个连续的1,若为偶数个,则最后一个0不用和前边的1凑对,否则必须凑对。
AC代码:
class Solution {
public:
bool isOneBitCharacter(vector<int>& bits) {
int length = bits.size();
bool ok = true;
if(bits[length-1]==0)
{
int pos = length-2;
int cnt = 0;
while(pos>=0&&bits[pos--]==1) cnt++;
if(cnt&1) ok = false;
}
else
ok = false;
return ok;
}
};