Skip to content

Instantly share code, notes, and snippets.

@sghall
Created January 23, 2017 06:25
Show Gist options
  • Save sghall/0822376f668fda0664e497d8474aa0fd to your computer and use it in GitHub Desktop.
Save sghall/0822376f668fda0664e497d8474aa0fd to your computer and use it in GitHub Desktop.
Determine if Brackets/Parenthesis are Nested Correctly
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