Last active
August 10, 2016 06:40
-
-
Save ikouchiha47/385786b9d42cdc3004b082768e5b4262 to your computer and use it in GitHub Desktop.
check string has balenced parenthesis
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 stack = []; | |
var Check = { | |
isOpen: (str) => ['{', '(', ']'].includes(str), | |
isClosed: (str) => ['}', ')', ']'].includes(str), | |
checkClosed: (i, j) => (i == '(' && j == ')') || (i == '{' && j == '}') || (i == '[' && j == ']'), | |
test: function(str) { | |
let unb = false; | |
str.split('').forEach((s) => { | |
if(this.isOpen(s)) { | |
stack.push(s); | |
} else if(this.isClosed(s)) { | |
let k = stack.pop(); | |
unb = this.checkClosed(k, s); | |
} | |
}); | |
return unb; | |
} | |
} | |
var Parenthesis = { | |
validParentheses: function(data) { | |
let brackets = '()[]{}' | |
let Stack = []; | |
data.split('').forEach(v => { | |
let bracePosition = brackets.indexOf(v); | |
if(bracePosition % 2 == 0) { | |
// if its an opening brace, push the close brace on stack; | |
Stack.push(bracePosition + 1); | |
} else { | |
// check if the closing brace being matched is the one on the top | |
if(!(Stack.length !== 0 && Stack.pop() === bracePosition)) throw new Error("unbalanced"); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment