Created
January 23, 2017 06:25
-
-
Save sghall/0822376f668fda0664e497d8474aa0fd to your computer and use it in GitHub Desktop.
Determine if Brackets/Parenthesis are Nested Correctly
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
const map = { '(': ')', '[': ']', '{': '}' }; | |
function nestedBrackets(s) { | |
const stack = []; | |
for (let i = 0; i < s.length; i++) { | |
if (s[i] === '{' || s[i] === '[' || s[i] === '(') { | |
stack.push(s[i]); | |
} else if (s[i] === '}' || s[i] === ']' || s[i] === ')') { | |
if (map[stack[stack.length - 1]] !== s[i]) { | |
return 0; | |
} | |
stack.pop(); | |
} | |
} | |
if (stack.length !== 0) { | |
return 0; | |
} | |
return 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment