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
相关推荐
EW Frontier7 分钟前
基于 Python + NumPy 的雷达信号处理仿真平台设计与实现——从 LFM 波形到 CFAR 检测的完整信号链
python·雷达信号处理·cfar\]·mti·mtd
axinawang16 分钟前
Tesseract入门--把图片里印刷文字提取成文本
python
青 春 记 忆28 分钟前
LeetCode 283. 移动零|Python 解法详解
python·算法·leetcode
人工干智能36 分钟前
科普:Python中的生成器——带`yield`的函数
开发语言·python
whcyhhh38 分钟前
头歌实践教学平台:数据科学与大数据技术导论(十四)
大数据·开发语言·python
清水白石00838 分钟前
Python dataclass 高级避坑指南:从 default_factory、frozen、slots 到哈希灾难
windows·python·哈希算法
在学了加油42 分钟前
阿尔茨海默病诊断(优化特征选择版)
人工智能·python·dnn
淼澄研学1 小时前
GPT-4o及mini模型参数解析与Python API调用实操
开发语言·python
kyrie_sakura2 小时前
python学习笔记 7--- 文件(IO)操作
笔记·python·学习