1106. Parsing A Boolean Expression #727
-
Topics: A boolean expression is an expression that evaluates to either
Given a string It is guaranteed that the given expression is valid and follows the given rules. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We will break down the solution into smaller functions that handle parsing and evaluating different types of expressions: Approach:
Let's implement this solution in PHP: 1106. Parsing A Boolean Expression <?php
/**
* @param String $expression
* @return Boolean
*/
function parseBooleanExpression($expression) {
$stack = [];
for ($i = 0; $i < strlen($expression); $i++) {
$char = $expression[$i];
if ($char == ')') {
// Process until we find a matching open parenthesis
$subExpr = [];
while ($stack && end($stack) != '(') {
array_unshift($subExpr, array_pop($stack));
}
array_pop($stack); // Remove the '('
// The operation comes before the '('
$operation = array_pop($stack);
// Evaluate the sub-expression
if ($operation == '&') {
$result = parse_and($subExpr);
} elseif ($operation == '|') {
$result = parse_or($subExpr);
} elseif ($operation == '!') {
$result = parse_not($subExpr);
}
// Push the result back to the stack as 't' or 'f'
$stack[] = $result ? 't' : 'f';
} elseif ($char != ',') {
// Push characters except ',' into the stack
$stack[] = $char;
}
}
// The result should be the final element in the stack
return $stack[0] == 't';
}
/**
* the logical AND
*
* @param $subExpr
* @return bool
*/
function parse_and($subExpr) {
foreach ($subExpr as $expr) {
if ($expr == 'f') {
return false;
}
}
return true;
}
/**
* the logical OR
*
* @param $subExpr
* @return bool
*/
function parse_or($subExpr) {
foreach ($subExpr as $expr) {
if ($expr == 't') {
return true;
}
}
return false;
}
/**
* the logical NOT
*
* @param $subExpr
* @return bool
*/
function parse_not($subExpr) {
// subExpr contains only one element for NOT operation
return $subExpr[0] == 'f';
}
// Test cases
echo parseBooleanExpression("&(|(f))") ? "true" : "false"; // Output: false
echo "\n";
echo parseBooleanExpression("|(f,f,f,t)") ? "true" : "false"; // Output: true
echo "\n";
echo parseBooleanExpression("!(&(f,t))") ? "true" : "false"; // Output: true
?> Explanation:
Example Walkthrough:
Complexity:
This solution is well-suited for the constraints and should handle the input size effectively. |
Beta Was this translation helpful? Give feedback.
We will break down the solution into smaller functions that handle parsing and evaluating different types of expressions:
parse_or
,parse_and
,parse_not
, and a mainparse
function that handles the parsing of the expression recursively. We will use a stack to keep track of nested expressions and evaluate them step-by-step.Approach:
Parsing and Recursion:
)
, extract the last set of expressions and apply the logical operation (&
,|
, or!
).Helper Functions:
parse_or
: Evaluates|(expr1, expr2…