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
相关推荐
_Jimmy_2 小时前
Agent 溯源精度提升方案
人工智能·python·langchain
SamChan903 小时前
在Web应用中集成PDF多语言翻译功能:PDFTranslator API实战指南
前端·python·ai·pdf·yapi·机器翻译
天天进步20153 小时前
Python全栈项目--智能办公自动化系统
开发语言·python
颜酱3 小时前
09 | 重构项目结构
人工智能·python·langchain
Sisphusssss5 小时前
香橙派5plus GPIO
linux·python·ubuntu
颜酱6 小时前
08 | 把维度值同步到 Elasticsearch(生成阶段)
人工智能·python·langchain
hanlin036 小时前
刷题笔记:力扣第242、349题(哈希表)
笔记·算法·leetcode
久久学姐6 小时前
基础转码学 AI:Java+Python 双语言入门,3 个月可落地实战项目
java·python·ai·转码·实战项目
ZHOU_WUYI6 小时前
4. light wam 模型loss计算过程
开发语言·人工智能·python
nwsuaf_huasir6 小时前
【无标题】
python