天天看點

[LeetCode]1-bit and 2-bit Characters 1位和2位字元

連結: https://leetcode.com/problems/1-bit-and-2-bit-characters/description/

難度:Easy

題目:717. 1-bit and 2-bit 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.

翻譯:給定兩種字元,一種用1位的0表示,另一種用2位10或者11表示。現在給出一個由很多位字元表示的字元串,判斷最後一位是不是1位字元。

思路:從頭到尾周遊,如果該位數字為1,則向後前進兩位,否則前進1位,循環的條件是i < n-1,即留出最後一位,是以當循環退出後,當i正好停留在n-1上,說明最後一位是單獨分割開的。

參考代碼:

Java

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