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
相关推荐
gwf21627 分钟前
磨损均衡算法(Wear Leveling)——SSD如何让每块闪存“公平退休“?
运维·数据库·人工智能·python·嵌入式硬件·算法·智能硬件
爱吃提升41 分钟前
python 分布式爬虫、爬虫合规与综合实战项目
分布式·爬虫·python
审小匠OpenCPAi42 分钟前
银行流水核查怎么自动化?单边匹配、双向勾稽与图聚类异常检测的工程对比
java·前端·人工智能·python·审计
元Y亨H2 小时前
Pandas 解析 Excel 导致的内存溢出(MemoryError)
python·excel
金銀銅鐵3 小时前
[Python] 用 turtle 来绘制瑞典国旗
python
Albert Edison3 小时前
【GUI 自动化测试】Pywinauto 常见操作
自动化测试·python·pywinauto
海兰3 小时前
【高速缓存】RedisVL为文本生成嵌入向量实践指南
人工智能·python·机器学习
2601_955760073 小时前
如何用 Claude Opus 5 API 批量扩展长尾关键词和文章选题
前端·python·搜索引擎
艾斯特_3 小时前
从模型调用到可用聊天应用:会话状态与消息协议
python·ai·aigc
alphaTao3 小时前
LeetCode 每日一题 2026/7/20-2026/7/26
算法·leetcode