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
相关推荐
Circ.8 小时前
wsl部署deerflow实现调用自定义的skill(demo级别调用)
python·大模型·deerflow
郝学胜-神的一滴8 小时前
PyTorch张量维度操控:transpose与permute深度拆解与实战指南
人工智能·pytorch·python·深度学习·算法·机器学习
小邓的技术笔记8 小时前
Python 入门:从“其他语言”到 Pythonic 思维的完整迁移手册
开发语言·python
北冥有羽Victoria8 小时前
Django 实战:SQLite 转 MySQL 与 Bootstrap 集成
大数据·服务器·python·django·编辑器
忘忧记8 小时前
Pytest + Requests + YAML 数据驱动+日志模块
网络·python·pytest
AI自动化工坊8 小时前
微软Agent Framework实战指南:统一Python和.NET的AI开发体验
人工智能·python·microsoft·.net·agent
林姜泽樾8 小时前
Python爬虫基础第一章,JSON
爬虫·python·网络爬虫
zzwq.8 小时前
深入理解Python闭包与装饰器:从入门到进阶
开发语言·python
网易独家音乐人Mike Zhou8 小时前
【Python】TXT、BIN文件的十六进制相互转换小程序
python·单片机·mcu·小程序·嵌入式·ti毫米波雷达
老四啊laosi8 小时前
[双指针] 5. 有效三角形的个数
算法·leetcode·有效三角形的个数