⚡Flashcard Drill➔
NeetCode #380LC-1106HardStack
← Back to All Problems

#380 · #1106 · Parsing A Boolean Expression(解析布尔表达式)

📌 Problem Statement & Constraints

A boolean expression is a string containing t (true), f (false), !(expr), &(expr,...) or |(expr,...). Evaluate it and return the result. Constraints: 1 <= expression.length <= 2 * 10^4; the expression is always valid.

💡 Core Algorithmic Approaches

  1. Use a stack. Push operators and operands as they appear; commas are skipped.
  2. On ), pop the operands belonging to the current group (they are the t/f characters on top), then pop the operator.
  3. Apply the operator: ! negates its single operand, & is all, | is any.
  4. Push the result back as t or f so it can participate in the enclosing group.

💻 Benchmark Python3 Implementation

class Solution:
    def parseBoolExpr(self, expression: str) -> bool:
        st = []
        for ch in expression:
            if ch == ",":
                continue                   # separators carry no information
            if ch in "tf!&|":
                st.append(ch)              # operand or operator
            else:                          # ch == ')'
                vals = []
                while st[-1] in "tf":      # collect this group's operands
                    vals.append(st.pop() == "t")
                op = st.pop()              # the operator for this group
                if op == "!":
                    st.append("t" if not vals[0] else "f")
                elif op == "&":
                    st.append("t" if all(vals) else "f")
                else:                      # '|'
                    st.append("t" if any(vals) else "f")
        return st[-1] == "t"

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each character is pushed or popped once, and the all/any scans are bounded by the number of operands in the group.
💾 Space Complexity
O(n) for the stack.

⚠️ Interview Pitfalls & Follow-ups

  • Not skipping commas: they would be pushed as if they were operands and break the grouping.
  • Popping the operator before the operands: the operands are on top, so they must be collected first.
  • Applying all/any to a single operand for !: ! takes exactly one operand, so vals[0] is used directly.
  • Returning the stack contents: the answer is whether the single remaining entry is t.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Stack Problems

中文速览与面试要点

解析布尔表达式

布尔表达式要么为 t (真),要么为 f (假),要么为 !(expr) (逻辑非)、 &amp;(expr, expr, ...) (逻辑与)或 |(expr, expr, ...) (逻辑或)。给你一个以字符串形式表述的布尔表达式 expression,返回该表达式的布尔值结果。约束:1 ≤ expression.length ≤ 2 × 10^4;expression 由 t 、 f 、 &amp; 、 | 、 ! 、 ( 、 ) 和 , 组成;expression 是一个有效的布尔表达式;每个 &amp; 、 | 都至少有两个参数。

核心要点

  • 栈 + 分治求值(标准解) :用栈保存「当前层的运算符」与「已求值的结果」。
  • 遇到运算符 &amp; / | / ! :把运算符压栈(跳过紧随的 ( )。
  • 遇到 t / f :把对应的布尔值压栈。
  • 遇到 , :跳过。
  • 遇到 ) :收集栈顶的所有布尔值(直到遇到运算符),根据运算符求值,把结果压回栈。
  • ! 只有一个操作数 , &amp; / | 有多个,需要循环收集。

常见陷阱

  • 遇到 ( 也压栈 :会把括号也当作元素,导致 isinstance(stack[-1], bool) 判断失效。应跳过 ( 与 , 。
  • ! 也循环收集多个操作数 : ! 只有一个操作数, not vals[0] 即可;若写成 not all(vals) 会出错。
  • 用递归解析 :可行但 s 长度可达 2 × 10^4,递归深度可能过大。栈方案更稳。
  • &amp; 与 | 的短路语义 :本题要求解析完整的表达式(不能短路,因为后面的子表达式也必须被解析),因此必须求值全部操作数。

参考实现

class Solution:
    def parseBoolExpr(self, expression: str) -> bool:
        stack = []
        for c in expression:
            if c in ('&', '|', '!'):
                stack.append(c)
            elif c == 't':
                stack.append(True)
            elif c == 'f':
                stack.append(False)
            elif c == ')':
                # 收集当前层的所有布尔值
                vals = []
                while isinstance(stack[-1], bool):
                    vals.append(stack.pop())
                op = stack.pop()                # 运算符
                if op == '&':
                    stack.append(all(vals))
                elif op == '|':
                    stack.append(any(vals))
                else:                           # '!'
                    stack.append(not vals[0])
            # '(' 和 ',' 直接跳过
        return stack[0]