-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparsingABooleanExpression.py
More file actions
35 lines (32 loc) · 972 Bytes
/
parsingABooleanExpression.py
File metadata and controls
35 lines (32 loc) · 972 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/parsing-a-boolean-expression/
# Author: Miao Zhang
# Date: 2021-04-09
class Solution:
def parseBoolExpr(self, expression: str) -> bool:
self.pos = 0
return self.parse(expression)
def parse(self, expression: str) -> bool:
ch = expression[self.pos]
self.pos += 1
if ch == 't': return True
if ch == 'f': return False
if ch == '!':
self.pos += 1
res = not self.parse(expression)
self.pos += 1
return res
isand = (ch == '&')
res = isand
self.pos += 1
while True:
if isand:
res &= self.parse(expression)
else:
res |= self.parse(expression)
if expression[self.pos] == ')':
self.pos += 1
break
self.pos += 1
return res