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
相关推荐
翔云12345623 分钟前
(MySQLdb._exceptions.OperationalError) (2006, ‘MySQL server has gone away‘)
网络·python
我是一只小青蛙88838 分钟前
Python办公自动化:6大实用库速览
python
Duang007_1 小时前
【LeetCodeHot100 超详细Agent启发版本】两数之和 (Two Sum)
java·人工智能·python
企业对冲系统官1 小时前
基差风险管理系统集成说明与接口规范
大数据·运维·python·算法·区块链·github
程序员-King.1 小时前
day134—快慢指针—环形链表(LeetCode-141)
算法·leetcode·链表·快慢指针
Swift社区1 小时前
LeetCode 376 摆动序列
算法·leetcode·职场和发展
花酒锄作田1 小时前
[python]Flask - Tracking ID的设计
python·flask·pytest
PeterClerk2 小时前
计算机视觉常用指标(Metrics)速查与解释(持续更新)
人工智能·python·深度学习·计算机视觉·benchmark·评测
哪有时间简史2 小时前
Python程序设计基础
开发语言·python
企业对冲系统官2 小时前
大宗商品风险对冲系统统计分析功能的技术实现
运维·python·算法·区块链·github·pygame