forked from lzl124631x/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths1.cpp
More file actions
32 lines (30 loc) · 714 Bytes
/
s1.cpp
File metadata and controls
32 lines (30 loc) · 714 Bytes
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
// OJ: https://leetcode.com/problems/design-compressed-string-iterator
// Author: github.com/lzl124631x
// Time: O(1)
// Space: O(1)
class StringIterator {
private:
string str;
int index = 0, nextIndex = 0, cnt = 0;
void load() {
while (index < str.size() && !cnt) {
index = nextIndex;
nextIndex = index + 1;
while (nextIndex < str.size() && isdigit(str[nextIndex])) cnt = cnt * 10 + str[nextIndex++] - '0';
}
}
public:
StringIterator(string compressedString) : str(compressedString) {
load();
}
char next() {
if (!hasNext()) return ' ';
char ans = str[index];
--cnt;
load();
return ans;
}
bool hasNext() {
return index < str.size();
}
};