350. Different Ways to Evaluate a Boolean Expression
You are given a string expr consisting of the characters
- 'T' ā represents true
- 'F' ā represents false
- '&' ā the logical AND operator
- '|' ā the logical OR operator
- '^' ā the logical XOR (exclusive-or) operator
expr is guaranteed to follow the pattern operand operator operand operator ⦠operand (i.e. it always starts and ends with an operand and no two operators are adjacent).
Return the number of distinct ways to fully parenthesize expr such that the whole expression evaluates to true.
Because the answer can be very large, return it modulo 109+7.
Example 1:
Input: expr = "T|T&F^T"
Output: 4
Explanation:
The expression can be parenthesized as follows (ā marks variants that evaluate to true):
1. ((T|T)&(F^T))Ā ā
2. (T|(T&(F^T)))Ā ā
3. (((T|T)&F)^T)Ā ā
4. (T|((T&F)^T))Ā ā
5. ((T|(T&F))^T)Ā Ā Ā ā false
6. (T|T)&F^TĀ Ā Ā Ā Ā ā false
Therefore 4 distinct parenthesizations evaluate to true.
Example 2:
Input: expr = "T^F|F"
Output: 2
Explanation:
Two parenthesizations evaluate to true:
⢠((T ^ F) | F)
⢠(T ^ (F | F))
Now Your Turn!
Pick the correct output for the given inputInput: expr = "T^F"
Still unsure what the problem is asking ?
Letās go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= expr.length <= 100
- expr[i] is 'T', 'F', '&', '|', or '^'.
- Operands ('T' or 'F') and operators alternate, so expr always has odd length.
- The answer fits in a signed 32-bit integer.