Design Compressed String Iterator

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class StringIterator:

    def __init__(self, compressedString: str):
        self.string = compressedString
        self.index = 0
        self.count = 0
        self.char = None

    def next(self) -> str:
        if not self.hasNext():
            return ' '
        if self.count == 0:
            self.char = self.string[self.index]
            self.index += 1
            while self.index < len(self.string) and self.string[self.index].isdigit():
                self.count = self.count * 10 + int(self.string[self.index])
                self.index += 1
        self.count -= 1
        return self.char

    def hasNext(self) -> bool:
        return self.index < len(self.string) or self.count > 0

Here’s how this works:

  • In the __init__ method, we initialize index at 0, which is the starting point in the compressed string. count is also set to 0, representing the number of occurrences of the current character to be returned, and char is the current character to be returned.

  • The next method checks whether there is a next character using the hasNext method. If there is no next character, it returns a whitespace. If the count of the current character is zero, it extracts the next character and its count from the compressed string.

  • The hasNext method checks whether there are any more characters in the compressed string to be returned. It returns true if there are still characters left to be returned, and false otherwise.