Problem
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
.
Examples
Example 1:
|
|
Constraints:
1 <= compressedString.length <= 1000
compressedString
consists of lower-case an upper-case English letters and digits.- The number of a single character repetitions in
compressedString
is in the range[1, 10^9]
- At most
100
calls will be made tonext
andhasNext
.
Solution
Method 1 – Two Pointers and Parsing
Intuition
We want to efficiently iterate through a compressed string like “a2b3” (which means “aabbb”) without decompressing the whole string. We can parse the string on the fly, keeping track of the current character and how many times it should be returned.
Approach
- Use two pointers: one to track the current position in the compressed string, and another to track the count of the current character.
- On initialization, parse the first character and its count.
- For
next()
, if the current count is zero, move to the next character and parse its count. - For
hasNext()
, check if there are any characters left to return. - Handle edge cases where the count is large or the string ends.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(1)
per operation. Eachnext
andhasNext
call does a constant amount of work, since parsing the number is only done when moving to a new character, and the number of such moves is limited by the number of operations (≤ 100). - 🧺 Space complexity:
O(1)
. Only a few variables are used, and we do not store the decompressed string.