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
相关推荐
askama004 小时前
Ubuntu安装Anaconda并配置环境
linux·python
计算机编程指导师4 小时前
【计算机毕设选题】基于Hadoop的电信网络诈骗话术语义特征挖掘分析系统源码 毕业设计 选题推荐 毕设选题 数据分析 机器学习
大数据·数据库·python
CS创新实验室4 小时前
Python 的鸭子类型
开发语言·windows·python
漂流瓶jz4 小时前
UVA-1610 聚会游戏 题解答案代码 算法竞赛入门经典第二版
数据结构·c++·算法·题解·aoapc·算法竞赛入门经典·uva
ThinkerQAQ_4 小时前
并发编程(七):volatile——从语言规则到 CPU
java·python·go
DanCheng-studio4 小时前
毕业设计项目 基于深度学习的图像修复算法 DCGAN
python·毕业设计·毕设
栈溢出了4 小时前
VS Code Python 自动导包失效排查笔记
开发语言·笔记·python
DanCheng-studio4 小时前
毕业设计项目 基于深度学习的抽烟行为检测算法实现(源码分享)
python·毕业设计·毕设
代码什么用5 小时前
LeetCode-560.和为 K 的子数组
算法·leetcode
Wx-bishekaifayuan5 小时前
springboot陨石鉴收系统96265-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·python·spring·课程设计