|
2 | 2 | # Space: O(n)
|
3 | 3 |
|
4 | 4 | class Solution(object):
|
| 5 | + def minOperationsToFlip(self, expression): |
| 6 | + """ |
| 7 | + :type expression: str |
| 8 | + :rtype: int |
| 9 | + """ |
| 10 | + def compute(operands, operators): |
| 11 | + right, left, op = operands.pop(), operands.pop(), operators.pop() |
| 12 | + if op == '&': |
| 13 | + operands.append([min(left[0], right[0]), |
| 14 | + min(left[1]+right[1], min(left[1], right[1])+1)]) |
| 15 | + else: |
| 16 | + operands.append([min(left[0]+right[0], min(left[0], right[0])+1), |
| 17 | + min(left[1], right[1])]) |
| 18 | + |
| 19 | + precedence = {'&':0, '|':0} |
| 20 | + operands, operators = [], [] |
| 21 | + for c in expression: |
| 22 | + if c.isdigit(): |
| 23 | + operands.append([int(c != '0'), int(c != '1')]) |
| 24 | + elif c == '(': |
| 25 | + operators.append(c) |
| 26 | + elif c == ')': |
| 27 | + while operators[-1] != '(': |
| 28 | + compute(operands, operators) |
| 29 | + operators.pop() |
| 30 | + elif c in precedence: |
| 31 | + while operators and operators[-1] in precedence and \ |
| 32 | + precedence[operators[-1]] >= precedence[c]: |
| 33 | + compute(operands, operators) |
| 34 | + operators.append(c) |
| 35 | + while operators: |
| 36 | + compute(operands, operators) |
| 37 | + return max(operands[-1]) |
| 38 | + |
| 39 | + |
| 40 | +# Time: O(n) |
| 41 | +# Space: O(n) |
| 42 | +class Solution2(object): |
5 | 43 | def minOperationsToFlip(self, expression):
|
6 | 44 | """
|
7 | 45 | :type expression: str
|
|
0 commit comments