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
相关推荐
深蓝海拓3 分钟前
PySide6从0开始学习的笔记(二十五) Qt窗口对象的生命周期和及时销毁
笔记·python·qt·学习·pyqt
Dfreedom.12 分钟前
开运算与闭运算:图像形态学中的“清道夫”与“修复匠”
图像处理·python·opencv·开运算·闭运算
2301_7903009616 分钟前
用Python读取和处理NASA公开API数据
jvm·数据库·python
葱明撅腚27 分钟前
利用Python挖掘城市数据
python·算法·gis·聚类
We་ct30 分钟前
LeetCode 36. 有效的数独:Set实现哈希表最优解
前端·算法·leetcode·typescript·散列表
Serendipity_Carl34 分钟前
1637加盟网数据实战(数分可视化)
爬虫·python·pycharm·数据可视化·数据清洗
流㶡37 分钟前
网络爬虫之requests.get() 之爬取网页内容
python·数据爬虫
yuankoudaodaokou1 小时前
高校科研新利器:思看科技三维扫描仪助力精密研究
人工智能·python·科技
tod1131 小时前
力扣高频 SQL 50 题阶段总结(四)
开发语言·数据库·sql·算法·leetcode
言無咎1 小时前
从规则引擎到任务规划:AI Agent 重构跨境财税复杂账务处理体系
大数据·人工智能·python·重构