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
相关推荐
白山编程大哥4 小时前
Java OutputStreamWriter 详解:从字符到字节的桥梁
java·开发语言·python
落羽的落羽4 小时前
【AI】快速理解AI应用的相关名词概念
linux·c++·人工智能·python·计算机网络·算法
Chasing__Dreams4 小时前
大模型应用开发--13--RAG 查询优化策略
python
Nil2085 小时前
leetcode 17电话号码的字母组合
算法·leetcode·职场和发展
“AI国潮设计-小江”5 小时前
《Python实战 | SDXL大模型批量生成“英歌舞海浪”蛋糕IP,附核心Prompt控制代码与IP授权变现思路》
人工智能·python·prompt·aigc
znnnk5 小时前
【Python】GUI 开发从入门到实战(三):PyQt/PySide 进阶之路
开发语言·python·pyqt
203号居民6 小时前
LeetCode hot 100 — 25. K 个一组翻转链表
算法·leetcode·链表
触底反弹7 小时前
面试被问到 Text2SQL,我用 DeepSeek 自己实现了一个
python·sqlite
Nil2087 小时前
leetcode 78子集
数据结构·算法·leetcode
2601_962295587 小时前
python+selenium实现自动化测试
自动化测试·python·selenium·学习心得·web端测试