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
相关推荐
8Qi85 分钟前
LeetCode 76. 最小覆盖子串(Minimum Window Substring)
数据结构·算法·leetcode·滑动窗口·哈希表
我的xiaodoujiao6 分钟前
API 接口自动化测试详细图文教程学习系列23--结合Pytest框架使用4-前后置处理
python·学习·测试工具·pytest
weixin_BYSJ19877 分钟前
springboot旅游管理系统04470(附源码+开发文档+部署教程)
java·spring boot·python·算法·django·flask·旅游
8Qi89 分钟前
LeetCode 209. 长度最小的子数组(Minimum Size Subarray Sum)
java·算法·leetcode·双指针·滑动窗口
kaico201829 分钟前
Python 在 Jenkins Pipeline 中的使用总结
开发语言·python·jenkins
多彩电脑30 分钟前
在Kivy中制造可移动控件
python
Zy_Yin12339 分钟前
拆解如何用anthropic金融agent做投研
人工智能·python·深度学习·金融·github
清水白石00839 分钟前
Python 变量的本质:从“盒子思维”到“引用思维”,彻底理解赋值到底发生了什么
java·python·ajax
yaoxin52112341 分钟前
423. Java 日期时间 API - DayOfWeek 和 Month 枚举
开发语言·python
燐妤1 小时前
Python工具使用:Pycharm
python·pycharm