Problem statement

https://leetcode.com/problems/design-compressed-string-iterator/

Solution

Let self.inde be current index in our string, self.count be counter, how many times we still need to repeat letter and self.ch be a current letter. Traverse string and just do what is asked: if we still can take the current symbol, take it, if we can not, take next symbol and parse number after it and decrease it by one

Complexity

Amortized time complexity of next is O(1), space complexity is O(1).

Code

class StringIterator:
    def __init__(self, compressedString):
        self.string = compressedString
        self.ind, self.count, self.ch = 0, 0, None
        self.length = len(self.string)

    def next(self):
        if not self.hasNext(): return ' '
        if self.count != 0:
            self.count -= 1
        else:
            self.ch = self.string[self.ind]
            self.ind += 1
            num = self.string[self.ind]
            while self.ind < self.length - 1 and self.string[self.ind + 1].isdigit():
                self.ind += 1
                num += self.string[self.ind]
            
            self.count = int(num) - 1
            self.ind += 1
        return self.ch

    def hasNext(self):
        return self.ind != self.length or self.count != 0