Last active
March 18, 2021 14:25
-
-
Save DNature/19274ea5db6386fee84dbd70944eaff4 to your computer and use it in GitHub Desktop.
Parenthesis/Brackets Matching using Stack algorithm (Javascript)
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
function matchParenthesis(str){ | |
const stack = [] | |
const opening = /(\(|\{|\[)/ | |
const closing = /(\)|\}|\])/ | |
if(!str || !str.length) return undefined | |
for(let i = 0; i < str.length; i++){ | |
let letter = str.charAt(i) | |
if(letter.match(opening)){ | |
stack.push(letter) | |
} else if(letter.match(closing)){ | |
if(stack[stack.length -1] === '('){ | |
stack.pop() | |
} else { | |
return false | |
} | |
} else if(!letter.match(opening) || !letter.match(closing)){ | |
return false | |
} | |
} | |
return stack.length === 0 | |
} | |
console.log(matchParenthesis("9")) | |
console.log(matchParenthesis("((()))")) | |
console.log(matchParenthesis(")")) | |
console.log(matchParenthesis("(")) | |
console.log(matchParenthesis("()()")) | |
console.log(matchParenthesis(")(")) | |
console.log(matchParenthesis("()))((")) | |
console.log(matchParenthesis("((()()))")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment