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
相关推荐
Ivanqhz11 小时前
寄存器分配的核心函数 allocate
java·开发语言·后端·python·rust
2501_9454235412 小时前
如何为开源Python项目做贡献?
jvm·数据库·python
全栈凯哥12 小时前
23.Python 魔术方法完全指南
python
2401_8845632412 小时前
使用Flask快速搭建轻量级Web应用
jvm·数据库·python
Tisfy12 小时前
LeetCode 1594.矩阵的最大非负积:动态规划O(mn)
leetcode·矩阵·动态规划·dp
AC赳赳老秦12 小时前
OpenClaw办公文档处理技能:批量转换PDF/Excel,提取数据高效办公
大数据·人工智能·python·django·去中心化·deepseek·openclaw
Frostnova丶12 小时前
LeetCode 1594.矩阵中最大的非负乘积
算法·leetcode·矩阵
We་ct12 小时前
LeetCode 162. 寻找峰值:二分高效求解
前端·算法·leetcode·typescript·二分·暴力
hanlin0312 小时前
刷题笔记:力扣第38题-外观数列
算法·leetcode
苦瓜小生12 小时前
AI-TestHub:我如何从零开发一个智能测试用例生成平台
人工智能·python·测试工具·github·测试用例·fastapi