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
相关推荐
Csvn13 小时前
🌟 LangChain 30 天保姆级教程 · Day 13|OutputParser 进阶!让 AI 输出自动转为结构化对象,并支持自动重试!
python·langchain
cch891813 小时前
Python主流框架全解析
开发语言·python
sg_knight13 小时前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
好运的阿财14 小时前
process 工具与子agent管理机制详解
网络·人工智能·python·程序人生·ai编程
张張40814 小时前
(域格)环境搭建和编译
c语言·开发语言·python·ai
weixin_4235339914 小时前
【Windows11离线安装anaconda、python、vscode】
开发语言·vscode·python
Ricky111zzz14 小时前
leetcode学python记录1
python·算法·leetcode·职场和发展
小白学大数据14 小时前
Selenium+Python 爬虫:动态加载头条问答爬取
爬虫·python·selenium
Hui Baby15 小时前
springboot读取配置文件
后端·python·flask
阿Y加油吧15 小时前
回溯法经典难题:N 皇后问题 深度解析 + 二分查找入门(搜索插入位置)
开发语言·python