-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0394-decode-string.js
More file actions
34 lines (30 loc) · 1.04 KB
/
0394-decode-string.js
File metadata and controls
34 lines (30 loc) · 1.04 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
/**
* Decode String
* Time Complexity: O(M)
* Space Complexity: O(M + N)
*/
var decodeString = function (s) {
const stringPointer = { value: 0 };
const parseSegment = (inputStr, currentIdx) => {
let currentBuild = "";
let currentMultiplier = 0;
while (currentIdx.value < inputStr.length) {
const charUnit = inputStr[currentIdx.value];
if (charUnit >= '0' && charUnit <= '9') {
currentMultiplier = currentMultiplier * 10 + Number(charUnit);
} else if (charUnit === '[') {
currentIdx.value++;
const nestedContent = parseSegment(inputStr, currentIdx);
currentBuild += nestedContent.repeat(currentMultiplier);
currentMultiplier = 0;
} else if (charUnit === ']') {
return currentBuild;
} else {
currentBuild += charUnit;
}
currentIdx.value++;
}
return currentBuild;
};
return parseSegment(s, stringPointer);
};