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
相关推荐
我搞slam3 小时前
快乐数--leetcode
算法·leetcode·哈希算法
应用市场5 小时前
构建自定义命令行工具 - 打造专属指令体
开发语言·windows·python
东方佑5 小时前
从字符串中提取重复子串的Python算法解析
windows·python·算法
西阳未落5 小时前
LeetCode——二分(进阶)
算法·leetcode·职场和发展
Dfreedom.5 小时前
一文掌握Python四大核心数据结构:变量、结构体、类与枚举
开发语言·数据结构·python·变量·数据类型
一半烟火以谋生5 小时前
Python + Pytest + Allure 自动化测试报告教程
开发语言·python·pytest
叶子丶苏7 小时前
第八节_PySide6基本窗口控件_按钮类控件(QAbstractButton)
python·pyqt
百锦再7 小时前
对前后端分离与前后端不分离(通常指服务端渲染)的架构进行全方位的对比分析
java·开发语言·python·架构·eclipse·php·maven
吃着火锅x唱着歌8 小时前
LeetCode 410.分割数组的最大值
数据结构·算法·leetcode
Blossom.1188 小时前
把AI“刻”进玻璃:基于飞秒激光量子缺陷的随机数生成器与边缘安全实战
人工智能·python·单片机·深度学习·神经网络·安全·机器学习