550. Design Compressed String Iterator
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 that needs to be uncompressed in the original string, otherwise returns false.
Example 1:
Input :
["StringIterator", "next", "next", "next", "next", "hasNext", "next", "next", "hasNext"]
[["a2b3c1"], [], [], [], [], [], [], [], []]
Output : [null, "a", "a", "b", "b", true, "b", "c", false]
Explanation :
StringIterator stringIterator = new StringIterator("a2b3c1");
stringIterator.next(); // return "a"
stringIterator.next(); // return "a"
stringIterator.next(); // return "b"
stringIterator.next(); // return "b"
stringIterator.hasNext(); // return True
stringIterator.next(); // return "b"
stringIterator.next(); // return "c"
stringIterator.hasNext(); // return False
Example 2:
Input :
["StringIterator", "next", "next", "next", "next", "hasNext", "next", "hasNext"]
[["x5y1"], [], [], [], [], [], [], []]
Output : [null, "x", "x", "x", "x", true, "x", true]
Explanation :
StringIterator stringIterator = new StringIterator("x5y1");
stringIterator.next(); // return "x"
stringIterator.next(); // return "x"
stringIterator.next(); // return "x"
stringIterator.next(); // return "x"
stringIterator.hasNext(); // return True
stringIterator.next(); // return "x"
stringIterator.hasNext(); // return True
Now Your Turn!
Pick the correct output for the given inputInput :
["StringIterator", "next", "hasNext", "next", "hasNext", "next", "next", "hasNext"]
[["m3n2"], [], [], [], [], [], [], []]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 ≤ compressedString.length ≤ 1000
- compressedString consists of lower-case and upper-case English letters and digits.
- The number of a single character's repetitions in compressedString is in the range [1, 109].
- At most 100 calls will be made to next and hasNext.