-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path394. Decode String.js
41 lines (37 loc) · 971 Bytes
/
394. Decode String.js
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
var decodeString = function (s) {
var findSubString = function (s, start) {
let stack = new Array();
stack.push(s.charAt(start++));
while (stack.length !== 0) {
if (s.charAt(start) === "]") {
stack.pop();
} else if (s.charAt(start) === "[") {
stack.push("[");
}
start++;
}
return start;
};
var decode = function (s, start, end) {
let result = "";
let current = start;
while (current <= end) {
let c = s.charAt(current);
while (c >= "0" && c <= "9") {
current++;
c = s.charAt(current);
}
if (current === start) {
result += s.charAt(current++);
} else {
let count = s.substring(start, current);
let end = findSubString(s, current);
result += decode(s, current + 1, end - 2).repeat(count);
current = end;
}
start = current;
}
return result;
};
return decode(s, 0, s.length - 1);
};