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
相关推荐
一晌小贪欢8 小时前
深入解析 Python 3.11 版本迭代:性能飞跃与更优雅的错误处理
python·python基础·python3·python3.11·python小白
理智.6298 小时前
根据requirements.txt 完成环境中的依赖库导入
python·conda·pip
Blossom.1188 小时前
用纯 NLP 打造「零样本」时序预测模型:文本化序列 + LLM 的实战路线
人工智能·python·深度学习·机器学习·自然语言处理·架构·transformer
小二·8 小时前
Python Web 开发进阶实战:AI 编排引擎 —— 在 Flask + Vue 中构建低代码机器学习工作流平台
前端·人工智能·python
sww_10268 小时前
智能问数系统(二):数据分析师Python
java·前端·python
wm10439 小时前
代码随想录第十天 栈和队列
开发语言·python
飞Link9 小时前
PyTorch 核心 API 完全手册:从基础张量到模型部署
人工智能·pytorch·python·深度学习·机器学习
Dxy12393102169 小时前
Python使用Playwright入门教程:从环境搭建到实战应用
开发语言·python·playwright
墨抒颖 msy.plus9 小时前
如何构建现代Agent以OpenManus为例
python·ai编程
爆打维c9 小时前
01BFS算法(例题:网格传送门旅游)
c语言·c++·python·算法·leetcode·广度优先