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
相关推荐
MZ_ZXD0012 小时前
springboot旅游信息管理系统-计算机毕业设计源码21675
java·c++·vue.js·spring boot·python·django·php
TracyCoder1232 小时前
LeetCode Hot100(34/100)——98. 验证二叉搜索树
算法·leetcode
全栈老石2 小时前
Python 异步生存手册:给被 JS async/await 宠坏的全栈工程师
后端·python
梨落秋霜3 小时前
Python入门篇【模块/包】
python
阔皮大师4 小时前
INote轻量文本编辑器
java·javascript·python·c#
小法师爱分享4 小时前
StickyNotes,简单便签超实用
java·python
深蓝电商API4 小时前
处理字体反爬:woff字体文件解析实战
爬虫·python
开源技术4 小时前
Claude Opus 4.6 发布,100万上下文窗口,越贵越好用
人工智能·python
We་ct4 小时前
LeetCode 56. 合并区间:区间重叠问题的核心解法与代码解析
前端·算法·leetcode·typescript
张3蜂4 小时前
深入理解 Python 的 frozenset:为什么要有“不可变集合”?
前端·python·spring