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
相关推荐
Tisfy4 分钟前
LeetCode 0020.有效的括号:栈匹配
算法·leetcode·字符串·题解·括号匹配
oooost22 分钟前
Jupyter Notebook 常用快捷键速查
ide·python·jupyter
Navigator_Z33 分钟前
LeetCode //C - 1276. Number of Burgers with No Waste of Ingredients
c语言·算法·leetcode
阿钱真强道36 分钟前
30 嵌入式操作系统 | 上位机界面:Flask 网页显示 + 控制闭环
后端·python·flask
ysu_031437 分钟前
Docker-Desktop-WSL2实战指南-Windows从安装配置到项目容器化
windows·python·docker·容器·composer·dockerfile·wsl2
想吃火锅10051 小时前
【leetcode】189.轮转数组js
开发语言·javascript·leetcode
郝学胜-神的一滴1 小时前
AI 编程智能体 02:AI智能体到底是什么
开发语言·人工智能·python·程序人生·pycharm
Guarding and trust1 小时前
python系列之多线程编程
python
梅雅达编程笔记2 小时前
03_网页表格数据抓取
爬虫·python·beautifulsoup·pandas·数据采集
迅猛龙办公室2 小时前
Python实现求两个数字之和
java·开发语言·python