Last active
February 3, 2017 01:40
-
-
Save SharpCoder/313303982381933e686f90f7098e86ea to your computer and use it in GitHub Desktop.
Balanced parenthesis problem
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
| var open = ["(", "{", "["]; | |
| var closed = [")", "}", "]"]; | |
| function isMatched(str) { | |
| var stack = []; | |
| if (str === null || str === undefined) return false; | |
| if (str.length == 1 ) return false; | |
| for (var i = 0; i < str.length; i++) { | |
| var character = str[i]; | |
| var openIndex = open.indexOf(character); | |
| var closedIndex = closed.indexOf(character); | |
| if (openIndex >= 0) { | |
| stack.push(character); | |
| } else if (closedIndex >= 0){ | |
| var match = open[closedIndex]; | |
| if (stack.pop() != match) { | |
| return false; | |
| } | |
| } else { | |
| // Determine what to do here. | |
| // Ask if we should consider non parenthesies as | |
| // a failure state or ignore them. | |
| return false; | |
| } | |
| } | |
| // If we have all open or all closed, this will catch | |
| // that state. | |
| return stack.length == 0; | |
| } | |
| console.log(isMatched("[{({})}]")); | |
| console.log(isMatched("[[{{({)}}]]")); | |
| console.log(isMatched("(")); | |
| console.log(isMatched("((")); | |
| console.log(isMatched("(A)")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment