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
相关推荐
6Hzlia7 小时前
【Hot 100 刷题计划】 LeetCode 78. 子集 | C++ 回溯算法题解
c++·算法·leetcode
喝凉白开都长肉的大胖子8 小时前
在 Matplotlib 中fontweight一般怎么设置
python·matplotlib
HAPPY酷9 小时前
Python高级架构师之路——从原理到实战
java·python·算法
Thomas.Sir9 小时前
第十三章:RAG知识库开发之【GraphRAG 从基础到实战】
python·ai·rag·graphrag
一个处女座的程序猿O(∩_∩)O10 小时前
Python基础知识大全:从零开始掌握Python核心语法
开发语言·python
小陈工10 小时前
Python Web开发入门(十一):RESTful API设计原则与最佳实践——让你的API既优雅又好用
开发语言·前端·人工智能·后端·python·安全·restful
deephub10 小时前
ADK 多智能体编排:SequentialAgent、ParallelAgent 与 LoopAgent 解析
人工智能·python·大语言模型·agent
FL162386312911 小时前
基于yolov26+pyqt5的混凝土墙面缺陷检测系统python源码+pytorch模型+评估指标曲线+精美GUI界面
python·qt·yolo
cxr82811 小时前
GPU 加速声场求解器 CUDA Kernel 实现细节 —— 高频超声传播仿真并行计算引擎
人工智能·python·目标跟踪
枫叶林FYL12 小时前
第10章 符号推理与神经符号AI
pytorch·python·深度学习