[LeetCode] Design Compressed String Iterator

604. 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()
  • hasNext() Returns true if there is any letter needs to be uncompressed in the original string, otherwise returns false.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class StringIterator {
deque<pair<char,int>> dq;
public:
StringIterator(string compressedString) {
for(int i = 0; i < compressedString.length();) {
char ch = compressedString[i];
i += 1;
int cnt = 0;
while(i < compressedString.length() and isdigit(compressedString[i])) {
cnt = cnt * 10 + compressedString[i++] - '0';
}
dq.push_back({ch,cnt});
}
}

char next() {
while(dq.size() and dq.front().second == 0) dq.pop_front();
if(dq.size()) dq.front().second -= 1;
return dq.size() ? dq.front().first : ' ';
}

bool hasNext() {
while(dq.size() and dq.front().second == 0) dq.pop_front();
return dq.size();
}
};

/**
* Your StringIterator object will be instantiated and called as such:
* StringIterator* obj = new StringIterator(compressedString);
* char param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/


Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/30/PS/LeetCode/design-compressed-string-iterator/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.