717. 1-bit and 2-bit Characters@python
阿新 • • 發佈:2018-09-30
bool else easy 移動 數字 個數字 xpl esc true
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.
原題地址: 1-bit and 2-bit Characters
難度: Easy
題意: 存在兩類數,一類是10或者11,另一類為0.將一個數組拆分為這兩類數,判斷最後一組數為0,比如上面例子,第一組數為[1,0],第二組數為[0]
思路:
對於數字1,後面的一個數字是1或者0都行,所以遇到以可以跳過1後面的值,遇到0,則移動一位
代碼:
class Solution(object): def isOneBitCharacter(self, bits): """ :type bits: List[int] :rtype: bool """ i = 0 while i < len(bits): if bits[i] == 1: i += 2 if i == len(bits): returnFalse else: i += 1 return True
時間復雜度: O(n)
空間復雜度: O(1)
717. 1-bit and 2-bit Characters@python