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
相关推荐
qq_4232339015 分钟前
Python深度学习入门:TensorFlow 2.0/Keras实战
jvm·数据库·python
林深现海31 分钟前
【刘二大人】PyTorch深度学习实践笔记 —— 第四集:反向传播(凝练版)
pytorch·python·numpy
Tisfy1 小时前
LeetCode 3637.三段式数组 I:一次遍历(三种实现)
算法·leetcode·题解·模拟·数组·遍历·moines
菩提树下的凡夫1 小时前
Python 环境管理工具
开发语言·python
索荣荣1 小时前
JavaToken实战指南:从原理到应用
开发语言·python
Albert Edison1 小时前
【Python】函数
java·linux·python·pip
2401_836563181 小时前
用Python读取和处理NASA公开API数据
jvm·数据库·python
AAD555888992 小时前
基于Faster RCNN的暴力行为检测模型优化与实现_1
python
难得的我们2 小时前
超越Python:下一步该学什么编程语言?
jvm·数据库·python
期末考复习中,蓝桥杯都没时间学了2 小时前
力扣刷题15
算法·leetcode·职场和发展