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
相关推荐
big_rabbit050212 小时前
[算法][力扣167]Two Sum II
算法·leetcode·职场和发展
怪侠_岭南一只猿13 小时前
爬虫阶段一实战练习题二:爬取当当网图书列表
css·爬虫·python·html
3DVisionary13 小时前
捕捉亚毫米级裂纹演化!DIC技术为裂纹扩展与抗裂研究带来全新方案
人工智能·python·3d·应变测量·金属3d打印·dic精度检验方法·各向异性
smchaopiao13 小时前
Python数据库操作:SQLAlchemy ORM指南
jvm·数据库·python
Eward-an13 小时前
LeetCode 76. 最小覆盖子串(详细技术解析)
python·算法·leetcode·职场和发展
李昊哲小课13 小时前
Python itertools模块详细教程
数据结构·python·散列表
小猪弟14 小时前
【app逆向】某壳逆向的wll-kgsa参数,signature参数
python·逆向·wll-kgsa·signature·
不想看见40414 小时前
Reverse Bits位运算基础问题--力扣101算法题解笔记
笔记·算法·leetcode
对方正在长头发22514 小时前
写了个 Windows 端口映射管理工具,再也不用敲命令了
python