当前位置:网站首页>Leetcode daily question solution: 717 1-bit and 2-bit characters - reverse order

Leetcode daily question solution: 717 1-bit and 2-bit characters - reverse order

2022-06-24 18:13:00 Xiaoxinxin's Xiaozhai

There are two special characters :

The first character can use one bit 0 To express
The second character can use two bits (10 or 11) To express 、
Give one with 0 Binary array at the end bits , If the last character must be one character , Then return to true .

Example 1:

Input : bits = [1, 0, 0]
Output : true
explain : The only encoding is a two bit character and a one bit character .
So the last character is a bit character .
Example 2:

Input : bits = [1, 1, 1, 0]
Output : false
explain : The only way to encode is two bit characters and two bit characters .
So the last character is not a bit character .
 

Answer key : If you can't understand the question, please read my last blog ( The explanation is very clear )- This blog is a better way to use , The last one was about violence - This passage uses the method of flashback - The last one in each list must be 0, Then we can find the penultimate one first 0, Set his position as i , The next one is i+1,n For the length of the list ,i +1 To n - 2 The number of direct characters is n - i - 2, If n - i - 2 For the even ( because 1 and 1  1 and 0 As long as it is an even number, it must be able to form a complete 2 The currency ), So the last 0 There must be something left , To meet the requirements of the topic , by true, Otherwise false. If it's an odd number , Will eat the last 0, return false.

class Solution:
    def isOneBitCharacter(self, bits: List[int]) -> bool:
        n = len(bits)  # Find the length of the list 
        i =  n - 2    # initial i The location of the for  n-2
        while i >= 0 and bits[i]:  # Loop traversal , When bit[i] by 0 When   Out of the loop 
            i -= 1
        return (n-i)%2 == 0  # Output results 

原网站

版权声明
本文为[Xiaoxinxin's Xiaozhai]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202211407230342.html