题目描述:
LeetCode 341. Flatten Nested List Iterator
Given a nested list of integers, implement an iterator to flatten it.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Example 1:
Given the list [[1,1],2,[1,1]]
,
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1]
.
Example 2:
Given the list [1,[4,[6]]]
,
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6]
.
题目大意:
给定一个嵌套的整数列表,实现一个迭代器将其展开。
每一个元素或者是一个整数,或者是一个列表 -- 其元素也是一个整数或者其他列表。
测试用例如题目描述。
解题思路:
利用栈(Stack)数据结构对嵌套列表展开,在hasNext方法内将下一个需要访问的整数元素准备好,详见代码。
Python代码:
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger(object):
# def isInteger(self):
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# :rtype bool
# """
#
# def getInteger(self):
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# :rtype int
# """
#
# def getList(self):
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# :rtype List[NestedInteger]
# """
class NestedIterator(object):
def __init__(self, nestedList):
"""
Initialize your data structure here.
:type nestedList: List[NestedInteger]
"""
self.stack = []
self.list = nestedList
def next(self):
"""
:rtype: int
"""
return self.stack.pop()
def hasNext(self):
"""
:rtype: bool
"""
while self.list or self.stack:
if not self.stack:
self.stack.append(self.list.pop(0))
while self.stack and not self.stack[-1].isInteger():
top = self.stack.pop().getList()
for e in top[::-1]:
self.stack.append(e)
if self.stack and self.stack[-1].isInteger():
return True
return False
# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())
本文链接:http://bookshadow.com/weblog/2016/04/17/leetcode-flatten-nested-list-iterator/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。