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
相关推荐
for_syq5 分钟前
trace抓取工具
android·python
Tisfy12 分钟前
LeetCode 3212.统计 X 和 Y 频数相等的子矩阵数量:前缀和
算法·leetcode·前缀和·矩阵
Pyeako14 分钟前
基于Qt和PaddleOCR的工业视觉识别报警系统开发
人工智能·python·深度学习·数码相机·opencv·ocr·pyqt5
未知鱼37 分钟前
Python安全开发asyncio(异步IO与高并发)
python·安全·网络安全·github
代码探秘者39 分钟前
【大模型应用】5.深入理解向量数据库
java·数据库·后端·python·spring·面试
小鸡吃米…40 分钟前
Python 网络爬虫
开发语言·爬虫·python
Sakinol#42 分钟前
Leetcode Hot 100 ——动态规划part01
leetcode·动态规划
2401_8320353442 分钟前
使用Python处理计算机图形学(PIL/Pillow)
jvm·数据库·python
dapeng28701 小时前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
PNP Robotics1 小时前
PNP机器人分享Frankal机器人等具身案例开发和实践
大数据·python·学习·机器人·开源