LeetCode 604: Design Compressed String Iterator Solution
Master LeetCode problem 604 (Design Compressed String Iterator), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation:
To design a compressed string iterator, we need to implement a class that takes a compressed string as input and allows iterating over each character in the uncompressed form. The compressed string consists of a sequence of characters followed by their frequencies.
We can use two pointers - one to keep track of the current character and another to keep track of the remaining count of that character. When iterating, we decrement the count until it becomes zero and move to the next character.
Algorithm:
- Initialize class variables to store the current character, count of that character, and the compressed string.
- Implement a constructor that takes the compressed string as input and initializes the class variables.
- Implement a
next()function that returns the next character in the uncompressed form. - Implement a
hasNext()function that checks if there are more characters to iterate over.
Time Complexity:
- Constructor: O(n), where n is the length of the compressed string.
- next(): O(1)
- hasNext(): O(1)
Space Complexity:
- O(n) to store the compressed string.
: :
Solution Code
class StringIterator {
private char ch;
private int count;
private int index;
private String compressedString;
public StringIterator(String compressedString) {
this.compressedString = compressedString;
this.index = 0;
this.count = 0;
this.ch = ' ';
}
public char next() {
if (count == 0) {
if (index >= compressedString.length()) {
return ' ';
}
ch = compressedString.charAt(index++);
while (index < compressedString.length() && Character.isDigit(compressedString.charAt(index))) {
count = count * 10 + (compressedString.charAt(index++) - '0');
}
}
count--;
return ch;
}
public boolean hasNext() {
return index < compressedString.length() || count > 0;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 604 (Design Compressed String Iterator)?
This page provides optimized solutions for LeetCode problem 604 (Design Compressed String Iterator) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 604 (Design Compressed String Iterator)?
The time complexity for LeetCode 604 (Design Compressed String Iterator) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 604 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 604 in Java, C++, or Python.