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
相关推荐
li99yo2 小时前
3DGS的复现
图像处理·pytorch·经验分享·python·3d·conda·pip
Dontla6 小时前
用pip install -e .开发Python包时,Python项目目录结构(项目结构)(可编辑安装editable install)
python·pip
Thomas.Sir6 小时前
第三章:Python3 之 字符串
开发语言·python·字符串·string
威联通网络存储7 小时前
告别掉帧与素材损毁:威联通 QuTS hero 如何重塑影视后期协同工作流
前端·网络·人工智能·python
Dxy12393102167 小时前
Python 根据列表中某字段排序:从基础到进阶
开发语言·windows·python
splage8 小时前
Java进阶——IO 流
java·开发语言·python
cliffordl8 小时前
设计模式(python)
python·设计模式
x_xbx8 小时前
LeetCode:34. 在排序数组中查找元素的第一个和最后一个位置
数据结构·算法·leetcode
always_TT8 小时前
从Python_Java转学C语言需要注意什么?
java·c语言·python