leetcode1106
Posted asenyang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode1106相关的知识,希望对你有一定的参考价值。
做了一个解,但是WA,54/70,这个无法通过的测试用例有300个字符,太复杂了,我现在无法通过测试用例分析出哪里写的不对,感觉换一个思路更好一些:
1 class Solution: 2 def parseBoolExpr(self, expression: str) -> bool: 3 n = len(expression) 4 opstack = [] 5 boolstack = [] 6 savenum = [] 7 curnum = 0 8 for i in range(n): 9 cur = expression[i] 10 if cur == ‘(‘: 11 if curnum > 0: 12 savenum.append(curnum) 13 curnum = 0 14 elif cur == ‘)‘: 15 op = opstack.pop(-1) 16 if op == ‘!‘: 17 boolstack[-1] = not boolstack[-1] 18 else: 19 if op == ‘&‘: 20 bsop = True 21 bn = len(boolstack) 22 blist = boolstack[bn-curnum:] 23 while curnum > 0: 24 boolstack.pop() 25 curnum -= 1 26 for b in blist: 27 bsop = bsop and b 28 boolstack.append(bsop) 29 else: 30 bsop = False 31 bn = len(boolstack) 32 blist = boolstack[bn-curnum:] 33 while curnum > 0: 34 boolstack.pop() 35 curnum -= 1 36 for b in blist: 37 bsop = bsop or b 38 boolstack.append(bsop) 39 if len(savenum) > 0: 40 pnum = savenum.pop(-1) 41 curnum = pnum + 1 42 else: 43 curnum = 1 44 elif cur == ‘&‘ or cur == ‘|‘ or cur == ‘!‘: 45 opstack.append(cur) 46 elif cur == ‘t‘ or cur == ‘f‘: 47 curnum += 1 48 bl = True if cur == ‘t‘ else False 49 boolstack.append(bl) 50 elif cur == ‘,‘: 51 continue 52 else: 53 print(‘error‘) 54 return boolstack.pop(-1)
下面给以AC的解,这个和我的思路接近,使用栈来存储运算顺序,使用set()来进行括号内部的运算,可以减少手工运算的错误。
1 class Solution(object): 2 def parseBoolExpr(self, expression): 3 """ 4 :type expression: str 5 :rtype: bool 6 """ 7 stack = [] 8 for e in expression: 9 if e in ‘!|&ft(‘: 10 stack.append(e) 11 if e == ‘)‘: 12 exp = set() 13 while stack: 14 b = stack.pop() 15 if b != ‘(‘: 16 exp.add(True if b == ‘t‘ else False) 17 else: 18 operator = stack.pop() 19 if operator == ‘&‘: 20 r = all(exp) 21 if operator == ‘|‘: 22 r = any(exp) 23 if operator == ‘!‘: 24 r = not all(exp) 25 stack.append(‘t‘ if r else ‘f‘) 26 break 27 return True if stack[-1] == ‘t‘ else False
至于那种转换成eval()的嘛……
以上是关于leetcode1106的主要内容,如果未能解决你的问题,请参考以下文章
leetcode1106. Parsing A Boolean Expression
LeetCode 1106 解析布尔表达式[栈] HERODING的LeetCode之路
Leetcode 1106. Parsing A Boolean Expression
leetcode 352 & leetcode 239 & leetcode 295 & leetcode 53 & leetcode 209