Python solution with Lazy initializer


  • 0
    class StringIterator(object):
        def __init__(self, compressedString):
            self.data = compressedString
            self.idx = -1
            self.decodeNext()
            
        def decodeNext(self):
            self.idx += 1
            if self.idx + 1 < len(self.data):
                self.cur = self.data[self.idx]
                end = self.idx + 1
                while end < len(self.data) and self.data[end].isdigit():
                    end += 1
                self.num = int(self.data[self.idx+1:end])
                self.idx = end - 1
    
        def next(self):
            if self.hasNext():
                ret = self.cur
                self.num -= 1
                if self.num <= 0:
                    self.decodeNext()
                return ret
            return " "
                
        def hasNext(self):
            return self.idx < len(self.data) and self.num > 0
    

Log in to reply
 

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