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
相关推荐
幻影123!44 分钟前
从零训练一个会下五子棋的AI
python·深度学习·神经网络·强化学习·五子棋·alpha zero·mokugo
Python私教2 小时前
Django 接入 AI 大模型实战:从零做一个流式聊天网站
人工智能·python·django
Python私教2 小时前
Django 接入 MCP 实战:让 AI 安全调用数据库和业务接口
人工智能·python·django
Python私教2 小时前
Django 搭建 AI 本地知识库:文档上传、向量检索与智能问答
人工智能·python·django
always_TT3 小时前
【Python 日志记录:logging 模块入门】
开发语言·python·php
lipku5 小时前
数字人直播开源项目LiveStream
python·开源·数字人·数字人直播
阿童木写作6 小时前
Python实现亚马逊商品图批量智能抠图教程
人工智能·python
axinawang6 小时前
第24课:while循环的应用
python
三亚兴嘉装饰6 小时前
三亚服装店装修
python
小柯南敲键盘6 小时前
速卖通AI图片翻译API集成实战
人工智能·python