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 分钟前
FunctionCall实现与Prompt调优
python·ai·prompt
AI 编程助手GPT22 分钟前
ChatGPT 新手入门与实战操作指南
开发语言·人工智能·git·python·chatgpt
原创小甜甜28 分钟前
OOM 排查复盘:Hutool 序列化 Request 导致 Java Heap Space
java·开发语言·python
gf132111130 分钟前
【精确查找python脚本是否在运行】
linux·前端·python
z2005093031 分钟前
今日算法(回溯全排列)
c++·算法·leetcode
zhangfeng113332 分钟前
DeepSeek V4 适配华为昇腾950 难度及开源情况
人工智能·pytorch·python·机器学习·华为·开源
MU在掘金9169540 分钟前
给AI Agent做一个代码大脑:我用Tree-sitter+ChromaDB+MCP搭了个代码知识库
git·python
噜噜噜阿鲁~41 分钟前
python学习笔记 | 11.5、面向对象高级编程-使用枚举类
笔记·python·学习
包子BI大数据1 小时前
2.COZE-RAG知识库搭建
python·ai·aigc
七夜zippoe1 小时前
DolphinDB自定义函数:UDF开发指南
开发语言·python·自定义函数·udf·dolphindb