Last active
August 14, 2018 13:41
-
-
Save xiaoyunyang/e8c0f9932e8c5cda93f1f87f32759e0a to your computer and use it in GitHub Desktop.
hasBalancedParen
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
// 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