栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Leetcode 2222. Number of Ways to Select Buildings [Python]

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Leetcode 2222. Number of Ways to Select Buildings [Python]

从Hint就差不多了,Hint大法好。首先计算截止于i位置有多少0 和1,同理计算截止于i位置有多少01 和10组合(1和0或 0和1不必连续),最后依据前两者计算截止于i位置有多少010 和101组合,返回截止于最后一位的010和101组合就是答案。

class Solution:
    def numberOfWays(self, s: str) -> int:
        toi_1 = [0] * len(s)
        toi_0 = [0] * len(s)
        
        toi_1[0] = 1 if s[0] =='1' else 0
        toi_0[0] = 1 if s[0] =='0' else 0
        
        for i in range(1, len(s)):
            if s[i] == '1':
                toi_1[i] = toi_1[i-1] + 1
                toi_0[i] = toi_0[i-1]
            else:
                toi_0[i] = toi_0[i-1] + 1
                toi_1[i] = toi_1[i-1]
        
        toi_01 = [0] * len(s)
        toi_10 = [0] * len(s)
        
        for i in range(1, len(s)):
            toi_01[i] = toi_01[i-1] if s[i] == '0' else toi_01[i-1] + toi_0[i-1]
            toi_10[i] = toi_10[i-1] if s[i] == '1' else toi_10[i-1] + toi_1[i-1]
        
        toi_010 = [0] * len(s)
        toi_101 = [0] * len(s)
        
        for i in range(2, len(s)):
            toi_010[i] = toi_010[i-1] if s[i] == '1' else toi_010[i-1] + toi_01[i-1]
            toi_101[i] = toi_101[i-1] if s[i] == '0' else toi_101[i-1] + toi_10[i-1]
         
        return toi_010[-1] + toi_101[-1]

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/953701.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号