-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecode-string.js
More file actions
57 lines (53 loc) · 1.09 KB
/
decode-string.js
File metadata and controls
57 lines (53 loc) · 1.09 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
50
51
52
53
54
55
56
57
/**
* @param {string} s
* @return {string}
*/
var decodeString = function(s) {
const num = /\d/;
let reps = [];
let strs = [];
let groups = 0;
let rep = 0;
let str = '';
let res = '';
for (let ii = 0; ii < s.length; ii++) {
let ch = s[ii];
if (ch === '[') {
groups++;
reps.push(rep);
strs.push(str);
rep = 0;
str = '';
} else if (ch === ']') {
groups--;
const temp = str;
str = strs.pop();
rep = reps.pop();
while(rep) {
str += temp;
rep--;
}
} else if (num.test(ch)) {
let temp = '';
while(num.test(ch)) {
temp += ch;
ch = s[++ii];
}
ii--;
rep = parseInt(temp);
} else {
str += ch;
}
if (!groups) {
res += str;
str = '';
}
}
return res + str;
};
console.log('expect', 'aaabcbc');
console.log('actual', decodeString('3[a]2[bc]'));
console.log('expect', 'accaccacc');
console.log('actual', decodeString('3[a2[c]]'));
console.log('expect', 'abcabccdcdcdef');
console.log('actual', decodeString('2[abc]3[cd]ef'));