-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0604-design-compressed-string-iterator.js
More file actions
49 lines (42 loc) · 1.25 KB
/
0604-design-compressed-string-iterator.js
File metadata and controls
49 lines (42 loc) · 1.25 KB
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
/**
* Design Compressed String Iterator
* Time Complexity: O(N)
* Space Complexity: O(M)
*/
var StringIterator = function (compressedString) {
this.characterSegments = [];
this.currentSegmentPointer = 0;
this.remainingCharsInSegment = 0;
let parsingIndex = 0;
while (parsingIndex < compressedString.length) {
const charValue = compressedString[parsingIndex];
parsingIndex++;
let numericValue = "";
while (
parsingIndex < compressedString.length &&
/\d/.test(compressedString[parsingIndex])
) {
numericValue += compressedString[parsingIndex];
parsingIndex++;
}
this.characterSegments.push([charValue, parseInt(numericValue, 10)]);
}
};
StringIterator.prototype.next = function () {
if (!this.hasNext()) {
return " ";
}
if (this.remainingCharsInSegment === 0) {
this.remainingCharsInSegment =
this.characterSegments[this.currentSegmentPointer][1];
}
const outputChar = this.characterSegments[this.currentSegmentPointer][0];
this.remainingCharsInSegment--;
if (this.remainingCharsInSegment === 0) {
this.currentSegmentPointer++;
}
return outputChar;
};
StringIterator.prototype.hasNext = function () {
return this.currentSegmentPointer < this.characterSegments.length;
};