leetcode 717. 1-bit and 2-bit Characters

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:

贪心

复制代码
class Solution(object):
    def isOneBitCharacter(self, bits):
        """
        :type bits: List[int]
        :rtype: bool
        """
        # greedy? YES
        # 0 => true
        # 10=> false
        # 010=> false
        # 0|10|11|0|10|10|11|11|0
        i = 0
        is_one_bit = False
        while i < len(bits):
            if bits[i] == 0:
                i += 1
                is_one_bit = True
            else:
                i += 2
                is_one_bit = False
        return is_one_bit
复制代码

 

posted @   bonelee  阅读(194)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
历史上的今天:
2017-03-20 bleve搜索引擎源码分析之索引——mapping和lucene一样,也有_all
2017-03-20 golang OOP面向对象
2017-03-20 插值搜索——本质和二分无异,是利用数据分布的规律来定查找点,其基本假设是数据分布均匀
2017-03-20 倒排索引的一些算法调研
2017-03-20 倒排索引优化 - 跳表求交集 空间换时间
2017-03-20 倒排索引优化 - 跳表求交集 空间换时间 贪心
点击右上角即可分享
微信分享提示