Why is this code failing?


  • 0
    S

    Why does following code fails for following input?

    ["StringIterator","next","next","next","next","next","next","hasNext","next","hasNext"]
    [["L2e2t2C2o2d2e23"],[],[],[],[],[],[],[],[],[]]

    The code produces correct output for above input when "Run" but fails when "Submitted"

        curCount = 0
        curCh    = ' '
        
        def __init__(self, compressedString):
            """
            :type compressedString: str
            """
            self.compressedString       = compressedString if compressedString is not None else ''
            self.curIndex               = 0
            self.end                    = True if len(self.compressedString) == 0 else False
    
    
        def next(self):
            """
            :rtype: str
            """
            if self.hasNext() or StringIterator.curCount > 0:
                if StringIterator.curCount <= 0:
                    StringIterator.curCh    = self.compressedString[self.curIndex]
                    StringIterator.curCount = 0
                    i = self.curIndex+1
                    num =''
                    while i < len(self.compressedString):
                        if self.compressedString[i].isdigit() == True:
                            num += self.compressedString[i]
                            i   += 1
                        else:
                            break
                    
                    if i == len(self.compressedString):
                        self.end = True
                    self.curIndex = i
                    StringIterator.curCount += int(num)
                    StringIterator.curCount -= 1
                    return StringIterator.curCh
                else:
                    StringIterator.curCount -= 1
                    return StringIterator.curCh
            else:
                return ' '
            
            
            
    
        def hasNext(self):
            """
            :rtype: bool
            """
            return self.end != True
            
    
    
    # Your StringIterator object will be instantiated and called as such:
    # obj = StringIterator(compressedString)
    # param_1 = obj.next()
    # param_2 = obj.hasNext()

  • 0
    Z

    you need to reset class attributes in the init method, read the problem's note carefully: Note: Please remember to RESET your class variables declared in StringIterator, as static/class variables are persisted across multiple test cases.

    and your code has some other bugs which you need to identify


Log in to reply
 

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