1. 程式人生 > >LeetCode 717. 1-bit and 2-bit Characters

LeetCode 717. 1-bit and 2-bit Characters

div 單個字符 給定 tchar whether for pre clas logs

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 always 0 or 1.

在這道題中,給定了兩類特殊字符,一類是一位字符:0;一類是兩位字符:10或11.

現給了一個由0和1組成的、且最後一位是0的數組,判斷能否將其正確分割,且最後一位是單個字符0.

思路:如果出現1,則必須跟後面的0或1組成一個兩位字符。因此從前往後遍歷,如果bits[i] = 1,則將bits[i + 1]改為1;循環結束後,如果數組最後一位是1,則一定是一個兩位字符,如果是0,則是一個一位字符。具體代碼如下:

public class Solution {
    public boolean
isOneBitCharacter(int[] bits){ for(int i = 0; i < bits.length - 1; i++){ if(bits[i] == 1){ bits[i + 1] = 1; i++; } } return bits[bits.length - 1] == 0; }

LeetCode 717. 1-bit and 2-bit Characters