-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbrackets.js
35 lines (32 loc) · 903 Bytes
/
brackets.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
// Same solution for Nested, passed 100% for both
function solution(S) {
const openBrackets = ['(', '{', '['];
const closeBrackets = [')', '}', ']'];
let len = S.length;
let stack = [];
let counter = 0;
if (len === 0) { return 1; }
if (len % 2 !== 0) { return 0; }
for(let i=0;i<len;i++) {
let s = S[i];
let idx = openBrackets.indexOf(s);
if (idx > -1) {
if (stack.length > 0 && stack[0] === idx) {
counter += idx+1;
} else {
stack.unshift(idx);
}
} else {
let idxA = closeBrackets.indexOf(s);
let idxB = stack[0];
if (idxA === idxB) {
stack.shift();
} else if (counter <= 0) {
return 0;
} else {
counter -= idxA+1;
}
}
}
return stack.length + counter > 0 ? 0 : 1;
}