Last active
July 27, 2017 01:54
-
-
Save antonybudianto/1d64e4ecc703833f6446530d86c64c8e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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++; | |
} 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--; | |
} | |
} | |
} | |
} | |
return stack.length+counter > 0 ? 0 : 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment