LeetCode 题解工作台

解析布尔表达式

布尔表达式 是计算结果不是 true 就是 false 的表达式。有效的表达式需遵循以下约定: 't' ,运算结果为 true 'f' ,运算结果为 false '!(subExpr)' ,运算过程为对内部表达式 subExpr 进行 逻辑非 (NOT)运算 '&(subExpr 1 , subEx…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

困难 · 栈·状态

bolt

答案摘要

对于这种表达式解析问题,我们可以使用栈来辅助解决。 从左到右遍历表达式 `expression`,对于遍历到的每个字符 :

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

布尔表达式 是计算结果不是 true 就是 false 的表达式。有效的表达式需遵循以下约定:

  • 't',运算结果为 true
  • 'f',运算结果为 false
  • '!(subExpr)',运算过程为对内部表达式 subExpr 进行 逻辑非(NOT)运算
  • '&(subExpr1, subExpr2, ..., subExprn)',运算过程为对 2 个或以上内部表达式 subExpr1, subExpr2, ..., subExprn 进行 逻辑与(AND)运算
  • '|(subExpr1, subExpr2, ..., subExprn)',运算过程为对 2 个或以上内部表达式 subExpr1, subExpr2, ..., subExprn 进行 逻辑或(OR)运算

给你一个以字符串形式表述的 布尔表达式 expression,返回该式的运算结果。

题目测试用例所给出的表达式均为有效的布尔表达式,遵循上述约定。

 

示例 1:

输入:expression = "&(|(f))"
输出:false
解释:
首先,计算 |(f) --> f ,表达式变为 "&(f)" 。
接着,计算 &(f) --> f ,表达式变为 "f" 。
最后,返回 false 。

示例 2:

输入:expression = "|(f,f,f,t)"
输出:true
解释:计算 (false OR false OR false OR true) ,结果为 true 。

示例 3:

输入:expression = "!(&(f,t))"
输出:true
解释:
首先,计算 &(f,t) --> (false AND true) --> false --> f ,表达式变为 "!(f)" 。
接着,计算 !(f) --> NOT false --> true ,返回 true 。

 

提示:

  • 1 <= expression.length <= 2 * 104
  • expression[i]'('')''&''|''!''t''f'',' 之一
lightbulb

解题思路

方法一:栈

对于这种表达式解析问题,我们可以使用栈来辅助解决。

从左到右遍历表达式 expression,对于遍历到的每个字符 cc

  • 如果 cc"tf!&|" 中的一个,我们直接将其入栈;
  • 如果 cc 是右括号 ')',我们将栈中元素依次出栈,直到遇到操作符 '!''&''|'。过程中我们用变量 ttff 记录出栈字符中 't''f' 的个数。最后根据出栈字符的个数和操作符计算得到新的字符 't''f',并将其入栈。

遍历完表达式 expression 后,栈中只剩下一个字符,如果是 't',返回 true,否则返回 false

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 是表达式 expression 的长度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
    def parseBoolExpr(self, expression: str) -> bool:
        stk = []
        for c in expression:
            if c in 'tf!&|':
                stk.append(c)
            elif c == ')':
                t = f = 0
                while stk[-1] in 'tf':
                    t += stk[-1] == 't'
                    f += stk[-1] == 'f'
                    stk.pop()
                match stk.pop():
                    case '!':
                        c = 't' if f else 'f'
                    case '&':
                        c = 'f' if f else 't'
                    case '|':
                        c = 't' if t else 'f'
                stk.append(c)
        return stk[0] == 't'
speed

复杂度分析

指标
时间O(n)
空间O(n)
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate effectively demonstrates understanding of stack-based state management.

  • question_mark

    Candidate uses recursion in a clear and effective way to handle nested operations.

  • question_mark

    Candidate implements helper functions that make the solution modular and readable.

warning

常见陷阱

外企场景
  • error

    Failing to correctly manage nested operations in the expression, leading to incorrect results.

  • error

    Not properly handling edge cases with multiple nested parentheses or complex operator combinations.

  • error

    Overcomplicating the solution by missing the stack's role in managing the expression's state.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Change the expression format to include additional boolean operations or nested expressions.

  • arrow_right_alt

    Implement this problem with different recursion depths or constraints, such as limiting parentheses.

  • arrow_right_alt

    Extend the problem to support more complex boolean operations like XOR or conditional (if-else).

help

常见问题

外企场景

解析布尔表达式题解:栈·状态 | LeetCode #1106 困难