Last active
June 9, 2018 22:15
-
-
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.
This file contains 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
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