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
相关推荐
workflower1 小时前
时序数据获取事件
开发语言·人工智能·python·深度学习·机器学习·结对编程
CoderYanger2 小时前
C.滑动窗口-求子数组个数-越长越合法——2799. 统计完全子数组的数目
java·c语言·开发语言·数据结构·算法·leetcode·职场和发展
C++业余爱好者2 小时前
Java 提供了8种基本数据类型及封装类型介绍
java·开发语言·python
AI Echoes3 小时前
构建一个LangChain RAG应用
数据库·python·langchain·prompt·agent
派大鑫wink3 小时前
从零到精通:Python 系统学习指南(附实战与资源)
开发语言·python
c骑着乌龟追兔子4 小时前
Day 38 官方文档的阅读
python
羸弱的穷酸书生4 小时前
国网 i1协议 python实现
开发语言·python
weixin_462022354 小时前
RAW-Adapter: Adapting Pre-trained Visual Model to Camera RAW Images
python·计算机视觉
电子硬件笔记4 小时前
Python语言编程导论第三章 编写程序
开发语言·python·编辑器
布谷歌4 小时前
在java中实现c#的int.TryParse方法
java·开发语言·python·c#