717. 1-bit and 2-bit Characters #2436
-
|
Topics: We have two special characters:
Given a binary array Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to determine if the last character in a binary array (ending with 0) must be a one-bit character. The two valid characters are:
The key is to traverse the array and decode the characters. If we end exactly at the last bit, it must be a one-bit character. Otherwise, if we skip over the last bit (meaning it was part of a two-bit character), it's not a one-bit character. Approach: We'll traverse the array from left to right. When we encounter a Let's implement this solution in PHP: 717. 1-bit and 2-bit Characters <?php
/**
* @param Integer[] $bits
* @return Boolean
*/
function isOneBitCharacter($bits) {
$i = 0;
$n = count($bits);
while ($i < $n - 1) {
if ($bits[$i] == 1) {
$i += 2;
} else {
$i += 1;
}
}
return $i == $n - 1;
}
// Test cases
echo isOneBitCharacter([1,0,0]) . "\n"; // Output: true
echo isOneBitCharacter([1,1,1,0]) . "\n"; // Output: false
?>Explanation:
This approach efficiently decodes the array in a single pass, ensuring optimal performance with O(n) time complexity and O(1) space complexity. |
Beta Was this translation helpful? Give feedback.
We need to determine if the last character in a binary array (ending with 0) must be a one-bit character. The two valid characters are:
010or11The key is to traverse the array and decode the characters. If we end exactly at the last bit, it must be a one-bit character. Otherwise, if we skip over the last bit (meaning it was part of a two-bit character), it's not a one-bit character.
Approach:
We'll traverse the array from left to right. When we encounter a
1, it must be the start of a two-bit character, so we skip the next bit. When we encounter a0, it's a one-bit character, so we move to the next bit. We continue until we reach or pass the last bit. If we land ex…