Created
February 7, 2020 10:53
-
-
Save Gosilama/6844042d6440cf6fea40a3a3ccb71df9 to your computer and use it in GitHub Desktop.
Check if a string of parenthesis has balanced parenthesis
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
const parenthesis = { | |
brace: ['(', ')'], | |
square: ['[', ']'], | |
curly: ['{', '}'] | |
}; | |
const parensKeys = Object.keys(parenthesis); | |
const isOpenParenthesis = (p) => { | |
for (let i = 0; i < parensKeys.length; i++) { | |
if (p === parenthesis[`${parensKeys[i]}`][0]) { | |
return true; | |
} | |
} | |
return false; | |
} | |
const parenthesisMatch = (closedParenthesis, openParenthesis) => { | |
for (let i = 0; i < parensKeys.length; i++) { | |
if (openParenthesis === parenthesis[`${parensKeys[i]}`][0] && closedParenthesis === parenthesis[`${parensKeys[i]}`][1]) { | |
return true; | |
} | |
} | |
return false; | |
} | |
const isParenthesisBalanced = (str) => { | |
const strArr = str.split(''); | |
const parenStack = []; | |
for (let i = 0; i < strArr.length; i++) { | |
const s = strArr[i]; | |
if (isOpenParenthesis(s)) parenStack.push(s); | |
else if (parenStack.length === 0 || !parenthesisMatch(s, parenStack.pop())) return false; | |
} | |
return parenStack.length === 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment