Last active
April 2, 2019 23:10
-
-
Save andarms/f9f5ce50289a7b15a6f4c7755ac67c7e to your computer and use it in GitHub Desktop.
v2 ahora si verifica correctamente casos como ([{}()]) y más complejos, sin embargo hay que recorrer todo el string.
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
var input1 = "{[()]}"; | |
var input2 = "{[({}])}"; | |
var input3 = "{{[[(())]]}}"; | |
var input4 = "{[({{}[((({({})}))]}]])}"; | |
var input5 = "([{}()])"; | |
var input6 = "([{}()]()[])"; | |
const matches = { | |
"{": "}", | |
"(": ")", | |
"[": "]" | |
}; | |
function isBalanced(input) { | |
if (input.length % 2 !== 0) return "NO"; | |
openBraches = []; | |
for (let c of input) { | |
if (matches[c]) { | |
openBraches.push(c); | |
} else { | |
if (matches[openBraches.pop()] != c) return "NO"; | |
} | |
} | |
return "YES"; | |
} | |
function isBalancedR(input, openBraches = []) { | |
if (input == "") return "YES"; | |
let c = input.substr(0, 1); | |
if (matches[c]) { | |
openBraches.push(c); | |
return isBalancedR(input.substr(1), openBraches); | |
} else { | |
return matches[openBraches.pop()] != c ? "NO" : isBalancedR(input.substr(1), openBraches); | |
} | |
} | |
console.log(isBalancedR(input2)); | |
console.log(isBalancedR(input6)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment