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
相关推荐
renzao_ai15 分钟前
本地 35B 大模型部署实战:Ollama 跑 Ornith-35B 全流程
python·llama·免费ai大模型
the局外人23 分钟前
学习 FastAPI 的 Day 4:完成用户系统与接口联调(完结)
后端·python·fastapi
青山木26 分钟前
Hot 100 --- 打家劫舍
java·数据结构·算法·leetcode·动态规划
AIFQuant39 分钟前
Python股票实时价格告警系统:WebSocket订阅与REST快照实战
开发语言·python·websocket·a股行情
名字还没想好☜1 小时前
Java Collectors.groupingBy 进阶:多级分组、下游收集器与统计聚合一次搞定
java·windows·后端·python·spring
阿明61 小时前
Leetcode: 283. 移动零
算法·leetcode·职场和发展
2601_962078231 小时前
Python接口自动化流程(pytest)
python·pytest·接口自动化·测试框架·断言
6Hzlia1 小时前
【Classic 150 刷题计划】 LeetCode 134. 加油站 | C++ 贪心算法与局部否决逻辑
c++·leetcode·贪心算法
6Hzlia2 小时前
【Classic 150 刷题计划】 LeetCode 274. H 指数 | C++ 二分答案法 (单调性降维打击)
c++·算法·leetcode
杨女士YRJ2 小时前
python+pytest+01
python·pytest