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
相关推荐
CoderYanger3 分钟前
A.每日一题:1967题+1331题
java·程序人生·算法·leetcode·面试·职场和发展·学习方法
kisbad5 分钟前
Day 012|Embedding 和向量数据库:知识库检索到底在检什么
数据库·python·embedding·agent
va学弟12 分钟前
LeetCode 热题 100 题解(1):哈希
python·算法·leetcode·哈希算法
言乐616 分钟前
Python实现基本搜索引擎
java·linux·开发语言·python·搜索引擎
FriendshipT28 分钟前
Ultralytics:解读C3k2模块
人工智能·pytorch·python·深度学习·目标检测
啦啦啦_999931 分钟前
Agent项目
python
乱写代码34 分钟前
LangChain学习--Document
python
风之所往_1 小时前
Python 3.11 新特性全面总结
python·python3.11
小小测试开发2 小时前
RAG检索评测实战:9种架构对比与自动化评估框架搭建
运维·人工智能·python·自动化
迷途呀2 小时前
conda使用指南
python·深度学习·机器学习·pycharm·conda