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
相关推荐
第404号工位16 分钟前
离职退电脑前别只点“清空回收站”!手把手教你彻底抹除凭证与数字痕迹
linux·python·架构
Metaphor69230 分钟前
使用 Python 在 Word 文档中添加、修改和删除变量
python·word
終不似少年遊*43 分钟前
【AI Coding实战方法论】从计划协作到架构护栏,一套能长期复用的工程流程
人工智能·python·团队开发·ai编程·ai coding·skills·上下文管理
lusklusklusk43 分钟前
Python 全局变量与局部变量区别——global 关键字、__main__ 块与作用域示例
开发语言·前端·python
文丑颜不良啊1 小时前
LeetCode1261~1280题目解析
java·leetcode
马剑威(威哥爱编程)1 小时前
Python 智能体开发实战 01:装了三遍环境还在报错?虚拟环境和 DeepSeek 一次配到位
开发语言·人工智能·python·agent
卷无止境1 小时前
Skill 的安全边界在哪里:风险来源、验证思路与用户可用的防线
后端·python
TomEval1 小时前
【测AI】第22篇:Agent 系统测试方法 — AI 学会“动手“了
人工智能·python·prompt·aigc·测试用例
速易达网络2 小时前
如何“训练”一个 .task 模型
python
Shaoshing2 小时前
LeetCode100 11. 盛最多水的容器
算法·leetcode