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 input

Input: 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.

Fun Facts

0
class Solution {
public:
int countTrue(string s) {
// Your code goes here
}
};
Ā 
Test Case

Input:

Expr