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
相关推荐
维克兜率天35 分钟前
【维克】复合型CTA:趋势+套利的双轮驱动
python·学习方法
伞伞悦读36 分钟前
【第76期】两张3行表左连接变5行:主键、validate与未匹配排查完整教程
人工智能·python
用户8356290780511 小时前
使用 Python 在 Excel 中添加和自定义迷你图
后端·python
用户8356290780512 小时前
使用 Python 在 Excel 图表中添加趋势线与回归方程
后端·python
特立独行的猫A2 小时前
一份 Markdown 发十个平台:cspub 一稿多投
java·后端·python
深蓝AI2 小时前
HTTPX 超时 1 秒,接口为何还能跑 2.4 秒?
python
CyrusYiVPP2 小时前
哪个用户会再来买?RFM模型+plotly画出用户分层,数据分析实战第2期
人工智能·python
文丑颜不良啊3 小时前
LeetCode1961~1980题目解析
java·leetcode
文丑颜不良啊3 小时前
LeetCode2001~2020题目解析
java·leetcode
李帅5154 小时前
用 CPU 做发票识别:从 OCR 文本行到结构化明细表的 4 个硬骨头
python