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
相关推荐
pursuit_csdn1 天前
LeetCode 1022. Sum of Root To Leaf Binary Numbers
算法·leetcode·深度优先
nimadan121 天前
**AI漫剧软件2025推荐,解锁高性价比创意制作新体验**
人工智能·python
踩坑记录1 天前
leetcode hot100 35. 搜索插入位置 medium 二分查找
leetcode
yunhuibin1 天前
GoogLeNet学习
人工智能·python·深度学习·神经网络·学习
易辰君1 天前
【Python爬虫实战】正则:中文匹配与贪婪非贪婪模式详解
开发语言·爬虫·python
秀儿还能再秀1 天前
正则表达式核心语法 + Python的 re 库中常用方法
python·正则表达式
xcLeigh1 天前
Python入门:Python3 正则表达式全面学习教程
python·学习·正则表达式·教程·python3
-海绵东东-1 天前
哈希表······················
算法·leetcode·散列表
多恩Stone1 天前
【C++ debug】在 VS Code 中无 Attach 调试 Python 调用的 C++ 扩展
开发语言·c++·python
XW01059991 天前
4-11判断素数
前端·python·算法·素数