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).php
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.ios
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,判斷最後一個數字是不是一個單獨的數組,用到了貪心算法,設置一個變量 i ,遍歷數組碰到 1 ,無論後面一位是什麼,都是一個合法的兩位數,因此直接 i+2 ,若是碰到 0,則 i+1 ,遍歷範圍是 i<len(bits)-1,最後判斷是否 i==len(bits)-1 。時間複雜度爲 O(N),空間複雜度爲 O(1)。less
class Solution(object):
def isOneBitCharacter(self, bits):
"""
:type bits: List[int]
:rtype: bool
"""
i = 0
while i<len(bits)-1:
if bits[i] == 0:
i+=1
else:
i+=2
return i == len(bits)-1
複製代碼
Runtime: 48 ms, faster than 17.47% of Python online submissions for 1-bit and 2-bit Characters.
Memory Usage: 11.9 MB, less than 15.00% of Python online submissions for 1-bit and 2-bit Characters.
複製代碼
每日格言:過去屬於死神,將來屬於你本身。yii