Python | Leetcode Python题解之第385题迷你语法分析器

题目:

题解:

python 复制代码
class Solution:
    def deserialize(self, s: str) -> NestedInteger:
        index = 0

        def dfs() -> NestedInteger:
            nonlocal index
            if s[index] == '[':
                index += 1
                ni = NestedInteger()
                while s[index] != ']':
                    ni.add(dfs())
                    if s[index] == ',':
                        index += 1
                index += 1
                return ni
            else:
                negative = False
                if s[index] == '-':
                    negative = True
                    index += 1
                num = 0
                while index < len(s) and s[index].isdigit():
                    num *= 10
                    num += int(s[index])
                    index += 1
                if negative:
                    num = -num
                return NestedInteger(num)

        return dfs()
相关推荐
shiming887923 分钟前
Python数据分析与可视化
开发语言·python·数据分析
William数据分析24 分钟前
Python数据分析与可视化实战指南
python·数据
Python之栈43 分钟前
Python if 语句优化技巧
python·算法
姑苏老陈1 小时前
【Python基础】Python文件处理
开发语言·python·python文件操作
yukai080081 小时前
Python 全栈系列271 微服务踩坑记
python·微服务·php
学步_技术2 小时前
Python编码系列—Python工厂方法模式:构建灵活对象的秘诀
开发语言·python·工厂方法模式
秋秋秋叶2 小时前
Python学习——【2.3】for循环
python·学习
会发paper的学渣2 小时前
python 单例模式实现
开发语言·python·单例模式
学步_技术2 小时前
Python编码系列—Python桥接模式:连接抽象与实现的桥梁
开发语言·python·桥接模式
柴华松2 小时前
GPU训练代码
开发语言·python