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
相关推荐
花酒锄作田2 小时前
Postgres - Listen/Notify构建轻量级发布订阅系统
python·postgresql
Boop_wu2 小时前
[Java 算法] 字符串
linux·运维·服务器·数据结构·算法·leetcode
Thomas.Sir2 小时前
第二章:LlamaIndex 的基本概念
人工智能·python·ai·llama·llamaindex
m0_694845572 小时前
Dify部署教程:从AI原型到生产系统的一站式方案
服务器·人工智能·python·数据分析·开源
李昊哲小课4 小时前
Python办公自动化教程 - 第7章 综合实战案例 - 企业销售管理系统
开发语言·python·数据分析·excel·数据可视化·openpyxl
不知名的老吴4 小时前
返回None还是空集合?防御式编程的关键细节
开发语言·python
李昊哲小课4 小时前
Python办公自动化教程 - 第5章 图表创建 - 让数据可视化
python·信息可视化·数据分析·数据可视化·openpyxl
chushiyunen4 小时前
python pygame实现贪食蛇
开发语言·python·pygame
Dream of maid4 小时前
Python-基础2(流程控制)
python
Lenyiin6 小时前
《Python 修炼全景指南:一》从环境搭建到第一个程序
开发语言·python