LeetCode717. 1比特与2比特字符(python3)

717. 1比特与2比特字符

在这里插入图片描述

法1:设置标志位,遍历数组。遇1索引加2,遇0索引加1

class Solution:
    def isOneBitCharacter(self, bits: List[int]) -> bool:

        index = 0
        while index<len(bits):
            if bits[index] == 1:
                index += 2
                flag = False
            else:
                index += 1
                flag = True
        return flag

优化优化:

既然bits数组中都是0,1则完全可以利用这些数字,写成一个统一的表达式index += bits[index] + 1

class Solution:
    def isOneBitCharacter(self, bits: List[int]) -> bool:
        #优化法1
        index = 0
        while index<len(bits)-1:
            print(index)
            index += bits[index] + 1
        return index == len(bits)-1

法3:贪心,最后一位一定要为0,不然一定不会满足;

最后一位为0后,判断之前连续的1的个数,如果为奇数则说明为11,10;如果为偶数,则说明,11,11,0

class Solution:
    def isOneBitCharacter(self, bits: List[int]) -> bool:
        #法3:贪心查看最后一位是否为0,查看最后一位之前的1的个数
        count,i = 1,len(bits)-1
        if bits[i]:
            return False
        else: 
            i = i-1
            while True:
                if bits[i] == 1:
                    count +=1
                    i -= 1
                else: break
            print(count)
            return count%2-1 == 0 

没有很大区别,就是想用三目运算

class Solution:
    def isOneBitCharacter(self, bits: List[int]) -> bool:
        #法3:贪心查看最后一位是否为0,查看最后一位之前的1的个数
        count,i = 0,len(bits)-1
        if bits[i]: return False
        else: 
            i = i-1
            while True:
                if bits[i] == 1:
                    count +=1
                    i -= 1
                else: break
            return count%2 == 0 if count!=0 else count == 0

法4:能迭代,一定能递归,

class Solution:
    def isOneBitCharacter(self, bits: List[int]) -> bool:
        return False if not bits or bits == [[1, 0]] else True if bits == [0] else self.isOneBitCharacter(bits[1:]) if bits[0] == 0 else self.isOneBitCharacter(bits[2:])
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南岸青栀*

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值