|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +CREATED AT: 2022-11-05 |
| 4 | +
|
| 5 | +URL: https://leetcode.com/problems/parsing-a-boolean-expression/ |
| 6 | +
|
| 7 | +GITHUB: https://github.com/Jiezhi/myleetcode |
| 8 | +
|
| 9 | +FileName: 1106-ParsingABooleanExpression |
| 10 | +
|
| 11 | +Difficulty: Hard |
| 12 | +
|
| 13 | +Desc: |
| 14 | +
|
| 15 | +Tag: |
| 16 | +
|
| 17 | +See: |
| 18 | +
|
| 19 | +""" |
| 20 | + |
| 21 | + |
| 22 | +class Solution: |
| 23 | + def parseBoolExpr(self, expression: str) -> bool: |
| 24 | + """ |
| 25 | + Runtime: 85 ms, faster than 73.11% |
| 26 | + Memory Usage: 14.1 MB, less than 61.79% |
| 27 | +
|
| 28 | + 1 <= expression.length <= 2 * 104 |
| 29 | + expression[i] is one following characters: '(', ')', '&', '|', '!', 't', 'f', and ','. |
| 30 | + """ |
| 31 | + if expression == 't': |
| 32 | + return True |
| 33 | + if expression == 'f': |
| 34 | + return False |
| 35 | + sub = expression[2:-1] |
| 36 | + if expression[0] == '!': |
| 37 | + return not self.parseBoolExpr(sub) |
| 38 | + elif expression[0] == '|': |
| 39 | + left = 0 |
| 40 | + cur = 0 |
| 41 | + for i, c in enumerate(sub): |
| 42 | + if c == '(': |
| 43 | + if left == 0: |
| 44 | + cur = i - 1 |
| 45 | + left += 1 |
| 46 | + elif c == ')': |
| 47 | + left -= 1 |
| 48 | + if left == 0: |
| 49 | + if self.parseBoolExpr(sub[cur:i + 1]): |
| 50 | + return True |
| 51 | + else: |
| 52 | + cur = i + 2 |
| 53 | + elif left == 0 and c == 't': |
| 54 | + return True |
| 55 | + return False |
| 56 | + elif expression[0] == '&': |
| 57 | + left = 0 |
| 58 | + cur = 0 |
| 59 | + for i, c in enumerate(sub): |
| 60 | + if c == '(': |
| 61 | + if left == 0: |
| 62 | + cur = i - 1 |
| 63 | + left += 1 |
| 64 | + elif c == ')': |
| 65 | + left -= 1 |
| 66 | + if left == 0: |
| 67 | + if not self.parseBoolExpr(sub[cur:i + 1]): |
| 68 | + return False |
| 69 | + else: |
| 70 | + cur = i + 2 |
| 71 | + elif left == 0 and c == 'f': |
| 72 | + return False |
| 73 | + return True |
| 74 | + |
| 75 | + |
| 76 | +def test(): |
| 77 | + assert Solution().parseBoolExpr(expression="|(f,f,f,!(f))") |
| 78 | + assert not Solution().parseBoolExpr(expression="&(|(f))") |
| 79 | + assert Solution().parseBoolExpr(expression="|(f,f,f,t)") |
| 80 | + assert Solution().parseBoolExpr(expression="!(&(f,t))") |
| 81 | + |
| 82 | + |
| 83 | +if __name__ == '__main__': |
| 84 | + test() |
0 commit comments