A/C Python solution, beat 77.72%, easy to understand


  • 0
    W

    class NestedIterator(object):
    def init(self, nestedList):
    """
    Initialize your data structure here.
    :type nestedList: List[NestedInteger]
    """
    self.newList = []
    self.curIdx = 0
    self.lenNewList = 0
    self.oriLen = len(nestedList)

        def helper(item):
            if item.isInteger() == True:
                # print "is integer, = ", item.getInteger()
                self.newList.append(item.getInteger())
                self.lenNewList += 1
            else:
                subList = item.getList()
                # print "subList = ", subList
                lenList = len(subList)
                # print "lenList = ", lenList
                for idx in range(lenList):
                    helper(subList[idx])
    
        for item in nestedList:
            helper(item)
    
            # print "self.newList = ", self.newList
            # print "self.lenNewList = ", self.lenNewList
    
    def next(self):
        """
        :rtype: int
        """
    
        if self.curIdx < self.lenNewList:
            nextData = self.newList[self.curIdx]
            self.curIdx += 1
            return nextData
        else:
            return
    
    def hasNext(self):
        """
        :rtype: bool
        """
    
        if self.curIdx < self.lenNewList:
            return True
        else:
            return False

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.