Skip to content

Instantly share code, notes, and snippets.

@DNature
Last active March 18, 2021 14:25
Show Gist options
  • Save DNature/19274ea5db6386fee84dbd70944eaff4 to your computer and use it in GitHub Desktop.
Save DNature/19274ea5db6386fee84dbd70944eaff4 to your computer and use it in GitHub Desktop.
Parenthesis/Brackets Matching using Stack algorithm (Javascript)
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