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
相关推荐
Forever Nore6 小时前
LeetCode 4 寻找两个正序数组的中位数 - 二分
算法·leetcode
北斗落凡尘6 小时前
LangGraph 入门实战(2)
python·langchain
ttod_qzstudio7 小时前
Java 常用语法极简通关(五):类与对象——字段、方法、构造器、this 与 static
java·开发语言·python
jufeng13078 小时前
【系列:手搓自主 AI Agent:Hermes 架构原理剖析 · 第 1 篇】
人工智能·python·架构·agent
月光船幽幽9 小时前
影子模式下保护 logits 不被修改
人工智能·python·算法
_oP_i11 小时前
python 后缀 mjs文件
开发语言·python
北斗落凡尘11 小时前
如何使用LangGraph(1)
python·langchain
Livia要学习12 小时前
Python装饰器
开发语言·python
evans在进步13 小时前
LeetCode 200:岛屿数量——Java DFS 染色法详解
java·leetcode·深度优先
大模型丫丫13 小时前
LangChain4j:Java 生态的 AI 应用开发利器
java·人工智能·python