Return the result of evaluating a given boolean expression
, represented as a string.
An expression can either be:
"t"
, evaluating toTrue
;"f"
, evaluating toFalse
;"!(expr)"
, evaluating to the logical NOT of the inner expressionexpr
;"&(expr1,expr2,...)"
, evaluating to the logical AND of 2 or more inner expressionsexpr1, expr2, ...
;"|(expr1,expr2,...)"
, evaluating to the logical OR of 2 or more inner expressionsexpr1, 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))"))