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
相关推荐
free-elcmacom6 小时前
深度学习<4>高效模型架构与优化器的“效率革命”
人工智能·python·深度学习·机器学习·架构
liliangcsdn6 小时前
python模拟beam search优化LLM输出过程
人工智能·python
源代码•宸7 小时前
Leetcode—620. 有趣的电影&&Q3. 有趣的电影【简单】
数据库·后端·mysql·算法·leetcode·职场和发展
王琦03187 小时前
Python 函数详解
开发语言·python
胡伯来了7 小时前
13. Python打包工具- setuptools
开发语言·python
小鸡吃米…8 小时前
Python 中的多层继承
开发语言·python
中國移动丶移不动8 小时前
Python MySQL 数据库操作完整示例
数据库·python·mysql
落叶,听雪8 小时前
AI建站推荐
大数据·人工智能·python
ZAz_8 小时前
DAY 45 预训练模型
python
呆萌很8 小时前
python 项目迁移
python