The problem is LeetCode 717: 1-bit and 2-bit Characters.
We have two special characters:
0
.10
or 11
).Given a binary array bits
that ends with 0
, we need to determine if the last character must be a one-bit character or not.
Function signature:
bool isOneBitCharacter(vector<int>& bits);
0
at the end?Input: bits = [1, 0, 0]
Output: true
Input: bits = [1, 1, 1, 0]
Output: false
To solve this problem, we’ll traverse through the array to understand how characters are formed:
bits
array from the start to determine the formation of characters until we reach the end.1
, it means the current character is formed by this 1
and the next bit (i.e., it is a two-bit character). Therefore, we should skip the next index.0
, it means the current character is a one-bit character.#include <vector>
using namespace std;
bool isOneBitCharacter(vector<int>& bits) {
int n = bits.size();
int i = 0;
while (i < n - 1) {
if (bits[i] == 1) {
i += 2;
} else {
i++;
}
}
// i should be on the position of the last bit, if i == n - 1, means the last bit is a single 0
return i == n - 1;
}
The given solution efficiently checks the formation of characters in the array and determines if the last character is a one-bit character.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?