1106. Parsing A Boolean Expression

给定一个表示布尔表达式的字符串,返回其评估结果。表达式可以是:真、假、非、与、或。利用栈来解析逆序波兰表达式,轻松解决此问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Return the result of evaluating a given boolean expression, represented as a string.

An expression can either be:

  • "t", evaluating to True;
  • "f", evaluating to False;
  • "!(expr)", evaluating to the logical NOT of the inner expression expr;
  • "&(expr1,expr2,...)", evaluating to the logical AND of 2 or more inner expressions expr1, expr2, ...;
  • "|(expr1,expr2,...)", evaluating to the logical OR of 2 or more inner expressions expr1, expr2, ...

 

Example 1:

Input: expression = "!(f)"
Output: true

Example 2:

Input: expression = "|(f,t)"
Output: true

Example 3:

Input: expression = "&(t,f)"
Output: false

Example 4:

Input: expression = "|(&(t,f,t),!(t))"
Output: false

 

Constraints:

  • 1 <= expression.length <= 20000
  • expression[i] consists of characters in {'(', ')', '&', '|', '!', 't', 'f', ','}.
  • expression is a valid expression representing a boolean, as given in the description.

思路:栈,还是逆序波兰表达,更easy

class Solution(object):
    def parseBoolExpr(self, expression):
        """
        :type expression: str
        :rtype: bool
        """
        st=[]
        for s in expression:
            if s==')':
                A=[]
                while st:
                    a=st.pop()
                    if a=='(': break
                    A.append(a)
                op=st.pop()
                if op=='&': st.append('f' if 'f' in A else 't')
                elif op=='|': st.append('t' if 't' in A else 'f')
                else: st.append('t' if A[0]=='f' else 'f')
            else:
                st.append(s)
                
        return True if st[-1]=='t' else False 
    
s=Solution()
print(s.parseBoolExpr("!(f)"))
print(s.parseBoolExpr("|(f,t)"))
print(s.parseBoolExpr("&(t,f)"))
print(s.parseBoolExpr("|(&(t,f,t),!(t))"))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值