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
相关推荐
写代码的【黑咖啡】6 分钟前
Python 中的 Requests 库:轻松进行 HTTP 请求
开发语言·python·http
栗子叶6 分钟前
Spring 中 Servlet 容器和 Python FastAPI 对比
python·spring·servlet·fastapi
杨杨杨大侠11 分钟前
DeepAgents 框架深度解析:从理论到实践的智能代理架构
后端·python·llm
袁袁袁袁满20 分钟前
Python读取doc文件打印内容
开发语言·python·python读取doc文件
m0_7482523835 分钟前
Ruby 模块(Module)的基本概念
开发语言·python·ruby
子午43 分钟前
【2026原创】水稻植物病害识别系统~Python+深度学习+人工智能+resnet50算法+TensorFlow+图像识别
人工智能·python·深度学习
深蓝电商API1 小时前
Scrapy ImagesPipeline和FilesPipeline自定义使用
爬虫·python·scrapy
木卫二号Coding1 小时前
Python-文件拷贝+文件重命名+shutil+记录
开发语言·python
老鼠只爱大米1 小时前
LeetCode算法题详解 56:合并区间
leetcode·并查集·合并区间·区间合并·线性扫描·算法面试
爬山算法1 小时前
Hibernate(44)Hibernate中的fetch join是什么?
前端·python·hibernate