Python | Leetcode Python题解之第341题扁平化嵌套列表迭代器

题目:

题解:

python 复制代码
class NestedIterator:
    def __init__(self, nestedList: [NestedInteger]):
        # 对于nestedList中的内容,我们需要从左往右遍历,
        # 但堆栈pop是从右端开始,所以我们压栈的时候需要将nestedList反转再压栈
        self.stack = nestedList[::-1]

    def next(self) -> int:
        # hasNext 函数中已经保证栈顶是integer,所以直接返回pop结果
        return self.stack.pop(-1).getInteger()

    def hasNext(self) -> bool: 
        # 对栈顶进行'剥皮',如果栈顶是List,把List反转再依次压栈,
        # 然后再看栈顶,依次循环直到栈顶为Integer。
        # 同时可以处理空的List,类似[[[]],[]]这种test case           
        while len(self.stack) > 0 and self.stack[-1].isInteger() is False:
            self.stack += self.stack.pop().getList()[::-1]
        return len(self.stack) > 0
相关推荐
HarmonLTS12 小时前
Python人工智能深度开发:技术体系、核心实践与工程化落地
开发语言·人工智能·python·算法
weixin_4624462312 小时前
Python 解析 Excel 图表(Chart)信息实战:从 xlsx 中提取标题、字体和数据
python·数据分析·excel·报表自动化
一分之二~13 小时前
二叉树--层序遍历(迭代和递归)
数据结构·c++·算法·leetcode
weixin_4624462313 小时前
使用 Python 脚本自动化管理 Docker 容器:启动、修改密码、删除及系统资源监控
python·docker·自动化·系统监控
weixin_4624462313 小时前
Python 异步下载文件实战:使用 asyncio + aiohttp 实现高并发下载
python·并发下载
bloglin9999913 小时前
anaconda环境中如何生成requirements
python
【赫兹威客】浩哥13 小时前
【赫兹威客】框架模板-后端bat脚本部署教程
python·django
Cestb0n13 小时前
某果app 加密校验算法逆向分析
python·算法·逆向安全
薛定谔的猫喵喵13 小时前
解决 xlrd 2.0+ 版本只支持 xls 格式的问题
python·excel
2501_9418053113 小时前
使用Python和Go构建高性能分布式任务调度系统的实践分享
分布式·python·golang