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
相关推荐
江华森13 小时前
Python神经网络编程(四):Python从零搭建神经网络
开发语言·python·神经网络
Sw1zzle20 小时前
算法入门(四):二叉树 - 递归遍历三件套
算法·leetcode
海石21 小时前
子树怎么找?树的3种遍历方式来帮忙!
算法·leetcode
海石21 小时前
难度分 1588:思路 + 技巧 = AC
算法·leetcode
nothing&nowhere1 天前
用 Python 做问卷数据清洗:无效样本检测与处理实战
开发语言·python·数据清洗·数据处理·问卷星·问卷星脚本·刷问卷
花酒锄作田1 天前
如何发布自己的 Python 库到 PyPI
python
researcher-Jiang1 天前
Design Patterns——Template Method入门到情景实战
python·设计模式·模板方法模式
飞猪~1 天前
LangChain python 版本 第一集
开发语言·python·langchain
2601_956319881 天前
最新AI量化提效,先做可验证的小流程
人工智能·python