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
相关推荐
小趴蔡ha3 小时前
02 Anaconda、Python 与机器学习开发环境入门
python·机器学习·anaconda
2401_868534783 小时前
RTOS之RT-Thread & Linux:线程/进程管理与调度核心差异分析
c++·python
mifengxing4 小时前
LeetCode 41.缺失的第一个正数|Hard题O(n)+O(1)最优解法深度解析
java·算法·leetcode·排序算法
数字化转型分享点滴4 小时前
富士康、蓝思科技为何选择四化信息?MES制造执行系统的实践
python·科技
wling03014 小时前
vasp虚频计算-python脚本
开发语言·windows·python·vasp计算
魔镜前的帅比4 小时前
(开源项目)x-claw(总)
python·ai·rust·开源
xrandzj5 小时前
Python面向对象编程入门:类、实例、初始化与封装实践
开发语言·python
matlabgoodboy8 小时前
计算机毕设代做|Java Python Matlab APP 全套开发设计
java·python·课程设计
用户8356290780518 小时前
Python Word 转 PDF 和 PDF 转 Word 指南
后端·python
用户8356290780518 小时前
如何使用 Python 加密和保护 Word 文档
后端·python