-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0880-decoded-string-at-index.js
More file actions
42 lines (38 loc) · 989 Bytes
/
0880-decoded-string-at-index.js
File metadata and controls
42 lines (38 loc) · 989 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
33
34
35
36
37
38
39
40
41
42
/**
* Decoded String At Index
* Time Complexity: O(s.length)
* Space Complexity: O(1)
*/
var decodeAtIndex = function (s, k) {
let currentTotalLength = 0;
let scanForwardIndex = 0;
while (currentTotalLength < k) {
let currentChar = s[scanForwardIndex];
if (currentChar.charCodeAt(0) >= 97 && currentChar.charCodeAt(0) <= 122) {
currentTotalLength++;
} else {
currentTotalLength *= parseInt(currentChar);
}
scanForwardIndex++;
}
let reverseTraverseIndex = scanForwardIndex - 1;
while (true) {
let backtrackChar = s[reverseTraverseIndex];
k %= currentTotalLength;
if (k === 0) {
k = currentTotalLength;
}
if (
backtrackChar.charCodeAt(0) >= 97 &&
backtrackChar.charCodeAt(0) <= 122
) {
if (k === currentTotalLength) {
return backtrackChar;
}
currentTotalLength--;
} else {
currentTotalLength /= parseInt(backtrackChar);
}
reverseTraverseIndex--;
}
};