Last active
July 7, 2019 04:50
-
-
Save shekohex/747440edb1e45810f368cc241e1436c5 to your computer and use it in GitHub Desktop.
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
/// https://leetcode.com/problems/parsing-a-boolean-expression | |
/** | |
* @param {string} expression | |
* @return {boolean} | |
*/ | |
var parseBoolExpr = function(expression) { | |
const stack = []; | |
for (let i = 0; i <= expression.length; ++i) { | |
const c = expression[i]; | |
if (c === '(' || c === ',') continue; | |
if (c === '!') stack.push(not); | |
else if (c === '&') stack.push(and); | |
else if (c === '|') stack.push(or); | |
else if (c === 't') stack.push(true); | |
else if (c === 'f') stack.push(false); | |
else if (c === ')') { | |
const params = []; | |
while (typeof stack[stack.length - 1] === 'boolean') { | |
params.push(stack.pop()); | |
} | |
const func = stack.pop(); | |
stack.push(func(params)); | |
} | |
} | |
return stack[stack.length - 1]; | |
}; | |
const not = xs => !xs[0]; | |
const or = xs => xs.some(x => x); | |
const and = xs => xs.every(x => x); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment