|
| 1 | +/** |
| 2 | + * 1106. Parsing A Boolean Expression |
| 3 | + * https://leetcode.com/problems/parsing-a-boolean-expression/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * A boolean expression is an expression that evaluates to either true or false. It can be in |
| 7 | + * one of the following shapes: |
| 8 | + * - 't' that evaluates to true. |
| 9 | + * - 'f' that evaluates to false. |
| 10 | + * - '!(subExpr)' that evaluates to the logical NOT of the inner expression subExpr. |
| 11 | + * - '&(subExpr1, subExpr2, ..., subExprn)' that evaluates to the logical AND of the inner |
| 12 | + * expressions subExpr1, subExpr2, ..., subExprn where n >= 1. |
| 13 | + * - '|(subExpr1, subExpr2, ..., subExprn)' that evaluates to the logical OR of the inner |
| 14 | + * expressions subExpr1, subExpr2, ..., subExprn where n >= 1. |
| 15 | + * |
| 16 | + * Given a string expression that represents a boolean expression, return the evaluation of |
| 17 | + * that expression. |
| 18 | + * |
| 19 | + * It is guaranteed that the given expression is valid and follows the given rules. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {string} expression |
| 24 | + * @return {boolean} |
| 25 | + */ |
| 26 | +var parseBoolExpr = function(expression) { |
| 27 | + const stack = []; |
| 28 | + |
| 29 | + for (const char of expression) { |
| 30 | + if (char === ')') { |
| 31 | + const operands = []; |
| 32 | + while (stack[stack.length - 1] !== '(') { |
| 33 | + operands.push(stack.pop()); |
| 34 | + } |
| 35 | + stack.pop(); |
| 36 | + const operator = stack.pop(); |
| 37 | + |
| 38 | + if (operator === '!') { |
| 39 | + stack.push(!operands[0]); |
| 40 | + } else if (operator === '&') { |
| 41 | + stack.push(operands.every(val => val)); |
| 42 | + } else if (operator === '|') { |
| 43 | + stack.push(operands.some(val => val)); |
| 44 | + } |
| 45 | + } else if (char !== ',') { |
| 46 | + stack.push(char === 't' ? true : char === 'f' ? false : char); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return stack[0]; |
| 51 | +}; |
0 commit comments