Design Compressed String Iterator Problem
Description
LeetCode Problem 604.
Design and implement a data structure for a compressed string iterator. The given compressed string will be in the form of each letter followed by a positive integer representing the number of this letter existing in the original uncompressed string.
Implement the StringIterator class:
next()Returns the next character if the original string still has uncompressed characters, otherwise returns a white space.hasNext()Returns true if there is any letter needs to be uncompressed in the original string, otherwise returnsfalse.
Example 1:
Input
["StringIterator", "next", "next", "next", "next", "next", "next", "hasNext", "next", "hasNext"]
[["L1e2t1C1o1d1e1"], [], [], [], [], [], [], [], [], []]
Output
[null, "L", "e", "e", "t", "C", "o", true, "d", true]
Explanation
StringIterator stringIterator = new StringIterator("L1e2t1C1o1d1e1");
stringIterator.next(); // return "L"
stringIterator.next(); // return "e"
stringIterator.next(); // return "e"
stringIterator.next(); // return "t"
stringIterator.next(); // return "C"
stringIterator.next(); // return "o"
stringIterator.hasNext(); // return True
stringIterator.next(); // return "d"
stringIterator.hasNext(); // return True
Constraints:
1 <= compressedString.length <= 1000compressedStringconsists of lower-case an upper-case English letters and digits.- The number of a single character repetitions in
compressedStringis in the range[1, 10^9] - At most
100calls will be made tonextandhasNext.
Solution
Approach: Parse Once into Runs
A count can be as large as 109, so expanding the string is out of the question. But we never need the expanded string: the iterator only has to know which letter comes next and how many copies of it are left.
In the constructor, scan the compressed string once and split it into runs (letter, count). A letter is followed by one or more digits, so keep reading digits and build the number with count = count * 10 + digit until the next letter. Then keep an index pos that points to the current run.
next(): if there is nothing left, return a space' '. Otherwise take the letter of the current run and decrease its count. When the count reaches0, moveposto the next run.hasNext(): there is something left exactly whenposhas not passed the last run. This works because we advanceposas soon as a run is used up, so the run atposalways has at least one copy left.
The easy-to-miss details are multi-digit counts ("a12" is twelve as, not one a and a stray 2) and calling next() after the end, which must return a space rather than fail.
Complexity: O(n) time to parse a compressed string of length n, then O(1) for each next and hasNext. O(n) space for the runs.
class StringIterator:
def __init__(self, compressedString: str):
# Parse once into (letter, count) runs; counts can have several digits.
self.runs = []
s, i = compressedString, 0
while i < len(s):
c = s[i]
i += 1
count = 0
while i < len(s) and s[i].isdigit():
count = count * 10 + int(s[i])
i += 1
self.runs.append([c, count])
self.pos = 0 # index of the current run
def next(self) -> str:
if not self.hasNext():
return " "
run = self.runs[self.pos]
run[1] -= 1
if run[1] == 0:
self.pos += 1
return run[0]
def hasNext(self) -> bool:
return self.pos < len(self.runs)