Python Iterator - Constant Memory


  • 0
    L
    class StringIterator(object):
    
        def __init__(self, compressedString):
            """
            :type compressedString: str
            """
            self.cs = compressedString
            self.it =0
            self.ccount = 0
            self.cchar = self.cs[self.it]
    
        def next(self):
            """
            :rtype: str
            """
            if self.it>=len(self.cs)-1 and self.ccount==0:
                return " "
            if self.ccount==0:
                self.cchar = self.cs[self.it]
                self.it+=1
                num_str = ""
                while self.it<len(self.cs) and self.cs[self.it].isnumeric():
                    num_str += self.cs[self.it]
                    self.it+=1
                    self.ccount =int(num_str)
            if self.ccount >0:
                self.ccount -=1
            return self.cchar
                
        def hasNext(self):
            """
            :rtype: bool
            """
            if self.it!=-1 and self.it<=len(self.cs)-1 or self.ccount>0:
                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.