Skip to main content

717. 1-bit and 2-bit Characters

Easy
Description

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).

Given a binary array bits that ends with 0, return true if the last character must be a one-bit character.

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: he only way to decode it is two-bit character and two-bit character. So the last character is not one-bit character.

Constraints:

  • 1 <= bits.length <= 1000
  • bits[i] is either 0 or 1.

解題思路

題目給一組只由 01 所組成的陣列,要判斷最後一位的 0 是否是單獨存在,而不是接續前面的 [1,0] 這樣的組合
最後一位一定會是 0,所以只需要到 bits.length - 1 就行
因為 return 時候會用到 i 來判斷結果,故不使用 for 選擇使用 while 迴圈來遍歷陣列

var isOneBitCharacter = function (bits) {
let i = 0;
while (i < bits.length - 1) {
if (bits[i] === 0) {
// 當前是 0 的話判斷下一個
i++;
} else {
// 不是 0 就代表當前是 1 ,且 1 一定會組成 [1,0] 或 [1,1],所以 += 2
i += 2;
}
}

return i === bits.length - 1;
// 如果 i === bits.length - 1 的話就代表只剩下一個 0 ,反之則否
};

心得

題目描述超不直觀,花了一點時間才看懂