Skip to content

Commit f21d700

Browse files
authored
Create parsing-a-boolean-expression.py
1 parent 2e1aea0 commit f21d700

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
class Solution(object):
5+
def parseBoolExpr(self, expression):
6+
"""
7+
:type expression: str
8+
:rtype: bool
9+
"""
10+
def parse(expression, i):
11+
if expression[i[0]] not in "&|!":
12+
result = expression[i[0]] == 't'
13+
i[0] += 1
14+
return result
15+
op = expression[i[0]]
16+
i[0] += 2
17+
stk = []
18+
while expression[i[0]] != ')':
19+
if expression[i[0]] == ',':
20+
i[0] += 1
21+
continue
22+
stk.append(parse(expression, i))
23+
i[0] += 1
24+
if op == '&':
25+
return all(stk)
26+
if op == '|':
27+
return any(stk)
28+
return not stk[0]
29+
30+
return parse(expression, [0])

0 commit comments

Comments
 (0)