Skip to content

Instantly share code, notes, and snippets.

@Rahul-Sagore
Last active June 9, 2018 22:15
Show Gist options
  • Save Rahul-Sagore/84cd0814c8096f4ab239685d5d6ab78b to your computer and use it in GitHub Desktop.
Save Rahul-Sagore/84cd0814c8096f4ab239685d5d6ab78b to your computer and use it in GitHub Desktop.
Program to examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in expression.
var balancedParanthesis = function (str) {
var openParnth = ['[', '{', '('], closedParanth = [']', '}', ')'];
var stack = [];
for (var i = 0; i < str.length; i++) {
if (openParnth.indexOf(str[i]) > -1) {
stack.push(str[i]);
}
if (closedParanth.indexOf(str[i]) > -1) {
var lastP = stack.pop();
var lastPIdx = openParnth.indexOf(lastP)
if(lastPIdx > -1 && lastPIdx != closedParanth.indexOf(str[i])) return false;
}
}
return stack.length ? false: true;
}
// Test with:
var str = "[()]{}{[()()]()}";
balancedParanthesis(str);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment