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
相关推荐
麦格芬2305 分钟前
LeetCode 763 划分字母区间
算法·leetcode·职场和发展
free-elcmacom10 分钟前
机器学习进阶<8>PCA主成分分析
人工智能·python·机器学习·pca
liu****43 分钟前
Python 基础语法(二):程序流程控制
开发语言·python·python基础
大连好光景1 小时前
Python打日志
运维·python·运维开发
syt_biancheng1 小时前
博客系统全流程测试总结
python·selenium·测试用例·压力测试·postman
可信计算1 小时前
【算法随想】一种基于“视觉表征图”拓扑变化的NLP序列预测新范式
人工智能·笔记·python·算法·自然语言处理
张广涛2 小时前
【无标题】
python
月明长歌2 小时前
【码道初阶】【LeetCode 110】平衡二叉树:如何用一个“Magic Number”将复杂度从O(N²)降为 O(N)?
linux·算法·leetcode
爱笑的眼睛112 小时前
超越剪枝与量化:下一代AI模型压缩工具的技术演进与实践
java·人工智能·python·ai
yaoh.wang2 小时前
力扣(LeetCode) 14: 最长公共前缀 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽