|
| 1 | +/** |
| 2 | + * @param {string} expression |
| 3 | + * @return {number} |
| 4 | + */ |
| 5 | +function minOperationsToFlip (s) { |
| 6 | + const nums = [] |
| 7 | + const ops = [] |
| 8 | + for (let i = 0; i < s.length; i++) { |
| 9 | + if (s[i] === '0') nums.push([0, 0, 1]) |
| 10 | + else if (s[i] === '1') nums.push([1, 1, 0]) |
| 11 | + else if (s[i] === '(') ops.push('(') |
| 12 | + else if (s[i] === ')') { |
| 13 | + while (ops.length && ops[ops.length - 1] !== '(') { |
| 14 | + const op = ops.pop() |
| 15 | + calc(op) |
| 16 | + } |
| 17 | + if (ops.length) ops.pop() |
| 18 | + } else { |
| 19 | + while (ops.length && grade(ops[ops.length - 1]) >= grade(s[i])) { |
| 20 | + const op = ops.pop() |
| 21 | + calc(op) |
| 22 | + } |
| 23 | + ops.push(s[i]) |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + while (ops.length && nums.length >= 2) { |
| 28 | + const op = ops.pop() |
| 29 | + calc(op) |
| 30 | + } |
| 31 | + const val = nums[0][0] |
| 32 | + return nums[0][2 - val] |
| 33 | + |
| 34 | + function calc (op) { |
| 35 | + const [x, y] = [nums.pop(), nums.pop()] |
| 36 | + let [z, a0, a1] = [0, 0, 0] |
| 37 | + switch (op) { |
| 38 | + case '&': |
| 39 | + z = x[0] & y[0] |
| 40 | + if (x[0] === 0 && y[0] === 0) { |
| 41 | + a0 = 0 |
| 42 | + a1 = Math.min(x[2] + 1, y[2] + 1) |
| 43 | + } |
| 44 | + if (x[0] === 0 && y[0] === 1) { |
| 45 | + a0 = 0 |
| 46 | + a1 = 1 |
| 47 | + } |
| 48 | + if (x[0] === 1 && y[0] === 0) { |
| 49 | + a0 = 0 |
| 50 | + a1 = 1 |
| 51 | + } |
| 52 | + if (x[0] === 1 && y[0] === 1) { |
| 53 | + a0 = Math.min(x[1], y[1]) |
| 54 | + a1 = 0 |
| 55 | + } |
| 56 | + break |
| 57 | + case '|': |
| 58 | + z = x[0] | y[0] |
| 59 | + if (x[0] === 0 && y[0] === 0) { |
| 60 | + a0 = 0 |
| 61 | + a1 = Math.min(x[2], y[2]) |
| 62 | + } |
| 63 | + if (x[0] === 0 && y[0] === 1) { |
| 64 | + a0 = 1 |
| 65 | + a1 = 0 |
| 66 | + } |
| 67 | + if (x[0] === 1 && y[0] === 0) { |
| 68 | + a0 = 1 |
| 69 | + a1 = 0 |
| 70 | + } |
| 71 | + if (x[0] === 1 && y[0] === 1) { |
| 72 | + a0 = Math.min(x[1] + 1, y[1] + 1) |
| 73 | + a1 = 0 |
| 74 | + } |
| 75 | + break |
| 76 | + } |
| 77 | + nums.push([z, a0, a1]) |
| 78 | + } |
| 79 | + function grade (op) { |
| 80 | + switch (op) { |
| 81 | + case '(': |
| 82 | + return 1 |
| 83 | + case '&': |
| 84 | + case '|': |
| 85 | + return 2 |
| 86 | + } |
| 87 | + return 0 |
| 88 | + } |
| 89 | +}; |
0 commit comments