1-bit and 2-bit Characters
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: True Explanation: 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: 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.
Note:
1 <= len(bits) <= 1000
.bits[i]
is always0
or1
.
题目比较暧昧= =细细理解下
1 class Solution { 2 public: 3 bool isOneBitCharacter(vector<int>& bits) { 4 5 int n = bits.size(); 6 7 for(int i = 0;i < n;) 8 { 9 if(bits[i]) 10 { 11 i += 2; 12 if(i >= n) 13 return false; 14 } 15 else 16 { 17 ++i; 18 } 19 } 20 return true; 21 } 22 };
之后看来一些更好的方法,可以把循环里面的二层嵌套的if提出来
class Solution { public: bool isOneBitCharacter(vector<int>& bits) { int n = bits.size(); int i = 0; for(;i < n - 1;)//最后一位一定为0 { if(bits[i]) { i += 2; } else { ++i; } } return i == n - 1 ? true:false; } };