Created
August 28, 2018 04:18
-
-
Save aykutyaman/3060d3cbe28cc0664276fc90b71cb386 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const isOpening = (s, m) => m[s]; | |
const isClosing = (s, m) => ( | |
Object.values(m).includes(s) | |
); | |
const isValid = (last, s, m) => ( | |
m[last] !== s | |
); | |
const balancedParens = s => { | |
const mapping = { | |
'(': ')', '[': ']' | |
}; | |
let stack = []; | |
let last; | |
for (var i = 0; i < s.length; i++) { | |
if (isOpening(s[i], mapping)) { | |
stack.push(s[i]); | |
} else if (isClosing(s[i], mapping)) { | |
last = stack.pop(); | |
if (isValid(last, s[i], mapping)) { | |
return false; | |
} | |
} | |
} | |
return stack.length === 0 ? true : false; | |
}; | |
let s = '()'; | |
console.log(balancedParens(s) === true); | |
s = '(())'; | |
console.log(balancedParens(s) === true); | |
s = '('; | |
console.log(balancedParens(s) === false); | |
s = '(()'; | |
console.log(balancedParens(s) === false); | |
s = '['; | |
console.log(balancedParens(s) === false); | |
s = '[]'; | |
console.log(balancedParens(s) === true); | |
s = '[)'; | |
console.log(balancedParens(s) === false); | |
s = '(((]))'; | |
console.log(balancedParens(s) === false); | |
s = '{ac[bb]}'; | |
console.log(balancedParens(s) === true); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment