Python | Leetcode Python题解之第306题累加数

题目:

题解:

python 复制代码
class Solution:
    def isAdditiveNumber(self, num: str) -> bool:
        n = len(num)
        for secondStart in range(1, n-1):
            if num[0] == '0' and secondStart != 1:
                break
            for secondEnd in range(secondStart, n-1):
                if num[secondStart] == '0' and secondStart != secondEnd:
                    break
                if self.valid(secondStart, secondEnd, num):
                    return True
        return False
    
    def valid(self, secondStart: int, secondEnd: int, num: str) -> bool:
        n = len(num)
        firstStart, firstEnd = 0, secondStart - 1
        while secondEnd <= n - 1:
            third = self.stringAdd(num, firstStart, firstEnd, secondStart, secondEnd)
            thirdStart = secondEnd + 1
            thirdEnd = secondEnd + len(third)
            if thirdEnd >= n or num[thirdStart:thirdEnd+1] != third:
                break
            if thirdEnd == n-1:
                return True
            firstStart, firstEnd = secondStart, secondEnd
            secondStart, secondEnd = thirdStart, thirdEnd
        return False
    
    def stringAdd(self, s: str, firstStart: int, firstEnd: int, secondStart: int, secondEnd: int) -> str:
        third = []
        carry, cur = 0, 0
        while firstEnd >= firstStart or secondEnd >= secondStart or carry != 0:
            cur = carry
            if firstEnd >= firstStart:
                cur += ord(s[firstEnd]) - ord('0')
                firstEnd -= 1
            if secondEnd >= secondStart:
                cur += ord(s[secondEnd]) - ord('0')
                secondEnd -= 1
            carry = cur // 10
            cur %= 10
            third.append(chr(cur + ord('0')))
        return ''.join(third[::-1])
相关推荐
liuze40811 分钟前
安装boss-zhipin-mcp(招聘)
开发语言·python
TickDB12 分钟前
Python 接入 A 股盘前集合竞价数据:AkShare 报错到 TickDB 实测的完整解法
python·websocket·行情数据 api
2601_9622982725 分钟前
【自动化测试】基于Selenium + Python的web自动化框架
自动化测试·python·selenium·测试用例·web框架
2601_9620775328 分钟前
Python 条件表达式
python·语法·列表推导式·条件表达式·pep308
右耳朵猫AI1 小时前
Python周刊2026W36 | Python 3.15候选版、RISC-V获CPython支持、PEP 843、asyncio修复
python·sqlite·risc-v
liliangcsdn1 小时前
基于信号强度的稀疏选股算法的探索分析
开发语言·python
shehuiyuelaiyuehao1 小时前
算法40,模拟运算,替换所有的问号
数据结构·算法·leetcode
小白快快跑哦1 小时前
python-字符串全解(四):字符串方法
开发语言·python·字符串
用户298698530142 小时前
Python 实现文本文件与 Word 文档互转的两种方法
后端·python·api