Skip to content

Instantly share code, notes, and snippets.

@xiaoyunyang
Last active August 14, 2018 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiaoyunyang/e8c0f9932e8c5cda93f1f87f32759e0a to your computer and use it in GitHub Desktop.
Save xiaoyunyang/e8c0f9932e8c5cda93f1f87f32759e0a to your computer and use it in GitHub Desktop.
hasBalancedParen
// Parentheses Tally
const newOpenCnt = (c, openCnt) => {
if (c === '(') return openCnt + 1
if (c === ')') return openCnt - 1
return openCnt
}
function isBalanced(str, openCnt) {
// Continue or Stop?
if (typeof str !== 'string') return false
if (openCnt < 0) return false
if (str.length === 0) return openCnt === 0
// What to Look At Next?
const fst = str[0]
const rst = str.slice(1)
return isBalanced(rst, newOpenCnt(fst, openCnt))
}
function hasBalancedParen(str) {
return isBalanced(str, 0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment