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
相关推荐
二川bro5 分钟前
2025年Python机器学习全栈指南:从基础到AI项目部署
人工智能·python·机器学习
Learn Beyond Limits40 分钟前
Correlation vs Cosine vs Euclidean Distance|相关性vs余弦相似度vs欧氏距离
人工智能·python·神经网络·机器学习·ai·数据挖掘
专注于大数据技术栈41 分钟前
java学习--==和equals
java·python·学习
testtraveler2 小时前
[Fix] ImportError: libtorch_cpu.so: undefined symbol: iJIT_NotifyEvent
pytorch·python·bug
lang201509282 小时前
Kafka延迟操作机制深度解析
分布式·python·kafka
测试老哥3 小时前
软件测试:测试用例的设计
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
koo3644 小时前
pytorch环境配置
人工智能·pytorch·python
yagamiraito_7 小时前
757. 设置交集大小至少为2 (leetcode每日一题)
算法·leetcode·go
程序员杰哥7 小时前
Python自动化测试之线上流量回放:录制、打标、压测与平台选择
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·压力测试
吴佳浩7 小时前
LangChain v1 重大更新讲解⚠⚠⚠
python·langchain·agent