LeetCode 0604. Design Compressed String Iterator Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0

Description

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 returns false.

 

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 <= 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 to next and hasNext.

Solutions

Solution 1: Parsing and Storing

Parse the compressedString into characters c and their corresponding repetition counts x, and store them in an array or list d. Use p to point to the current character.

Then perform operations in next and hasNext.

The initialization time complexity is O(n), and the time complexity of the other operations is O(1). Here, n is the length of compressedString.

PythonJavaC++GoTypeScript
class StringIterator: def __init__(self, compressedString: str): self.d = [] self.p = 0 n = len(compressedString) i = 0 while i < n: c = compressedString[i] x = 0 i += 1 while i < n and compressedString[i].isdigit(): x = x * 10 + int(compressedString[i]) i += 1 self.d.append([c, x]) def next(self) -> str: if not self.hasNext(): return ' ' ans = self.d[self.p][0] self.d[self.p][1] -= 1 if self.d[self.p][1] == 0: self.p += 1 return ans def hasNext(self) -> bool: return self.p < len(self.d) and self.d[self.p][1] > 0 # Your StringIterator object will be instantiated and called as such: # obj = StringIterator(compressedString) # param_1 = obj.next() # param_2 = obj.hasNext()(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !