-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.cpp
53 lines (44 loc) · 1.22 KB
/
Solution.cpp
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <cstddef>
#include <string>
using namespace std;
class StringIterator {
char c;
int repeats;
const std::string compressedString;
size_t idx;
public:
// No need to check
StringIterator(string compressedString)
: c(' '),
repeats(0),
compressedString(std::move(compressedString)),
idx(0) {}
char next() {
// the compressed string has the format CharDigit
if (!hasNext()) {
return ' ';
}
if (repeats > 0) {
--repeats;
return c;
}
// Otherwise, there is no more repeats.
// Advance the iterator, parse the next set of characters..
// There is no need to check that the iterator is at the end. Covered by
// the hasNext check above.
c = compressedString[idx++];
// parse the number of repeats
while (isdigit(compressedString[idx])) {
repeats = (repeats * 10) + (compressedString[idx++] - '0');
}
--repeats;
return c;
}
bool hasNext() { return repeats > 0 || idx < compressedString.length(); }
};
/**
* 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();
*/