Solve the Logical Expression given by string

Given a string str representing a logical expression which consists of the operators | (OR) , & (AND) , ! (NOT) , 0 , 1 and , only (i.e. no space between characters). The task is to print the result of the logical expression.

Examples:

Input: str = “[[0,&,1],|,[!,1]]”
Output: 0
[[0,&,1],|,[!,1]]
[[0,&,1],|,0]
[[0,&,1],|,0]
[0,|,0]
[0,|,0]

0

Input: str = “[!,[[0,&,[!,1]],|,[!,[[!,0],&,1]]]]”
Output: 1

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach:

1. Start traversing the string from the end.
2. If [ found go to Step-3 otherwise push the characters into the stack.
• Pop characters from stack until the stack top becomes “]”. > Insert each popped character into the vector.
• If the stack top becomes ] after 5 pop operations then the vector will be x, |, y or x, &, y.
• If the stack top becomes ] after 3 pop operations then the vector will be !, x.
• Pop ] from the stack top.
3. Perform the respective operations on the vector elements then push the result back into the stack.
4. If string is fully traversed then return the value at stack top otherwise go to step 2.

Below is the implementation of the above approach:

C++

 // C++ program to solve the logical expression. #include using namespace std;    // Function to evaluate the logical expression char logicalExpressionEvaluation(string str) {     stack arr;        // traversing string from the end.     for (int i = str.length() - 1; i >= 0; i--)      {         if (str[i] == '[')          {             vector s;             while (arr.top() != ']')             {                 s.push_back(arr.top());                 arr.pop();             }             arr.pop();                // for NOT operation             if (s.size() == 3)             {                 s == '1' ? arr.push('0') : arr.push('1');             }             // for AND and OR operation             else if (s.size() == 5)             {                 int a = s - 48, b = s - 48, c;                 s == '&' ? c = a & b : c = a | b;                 arr.push((char)c + 48);             }         }         else         {             arr.push(str[i]);         }     }     return arr.top(); }    // Driver code int main() {     string str = "[[0,&,1],|,[!,1]]";        cout << logicalExpressionEvaluation(str) << endl;        return 0; }

Java

 // Java program to solve the logical expression. import java.util.*;    class GFG  {        // Function to evaluate the logical expression static char logicalExpressionEvaluation(String str) {     Stack arr = new Stack();        // traversing string from the end.     for (int i = str.length() - 1; i >= 0; i--)      {         if (str.charAt(i) == '[')          {             Vector s = new Stack();             while (arr.peek() != ']')             {                 s.add(arr.peek());                 arr.pop();             }             arr.pop();                // for NOT operation             if (s.size() == 3)             {                 arr.push(s.get(2) == '1' ? '0' : '1');             }                            // for AND and OR operation             else if (s.size() == 5)             {                 int a = s.get(0) - 48,                      b = s.get(4) - 48, c;                 if(s.get(2) == '&' )                 {                     c = a & b;                 }                 else                 {                     c = a | b;                 }                 arr.push((char)(c + 48));             }         }         else         {             arr.push(str.charAt(i));         }     }     return arr.peek(); }    // Driver code public static void main(String[] args) {     String str = "[[0,&,1],|,[!,1]]";        System.out.println(logicalExpressionEvaluation(str)); } }    // This code is contributed by 29AjayKumar

Python3

 # Python3 program to solve the  # logical expression. import math as mt    # Function to evaluate the logical expression def logicalExpressionEvaluation(string):        arr = list()        # traversing string from the end.     n = len(string)     for i in range(n - 1, -1, -1):         if (string[i] == "["):                s = list()                while (arr[-1] != "]"):                 s.append(arr[-1])                 arr.pop()                arr.pop()                # for NOT operation             if (len(s) == 3):                 if s == "1":                     arr.append("0")                 else:                     arr.append("1")                # for AND and OR operation             elif (len(s) == 5):                 a = int(s) - 48                 b = int(s) - 48                 c = 0                 if s == "&":                     c = a & b                 else:                     c = a | b                 arr.append((c) + 48)                        else:             arr.append(string[i])        return arr[-1]    # Driver code string= "[[0,&,1],|,[!,1]]"    print(logicalExpressionEvaluation(string))    # This code is contributed  # by mohit kumar 29

Output:

0

Time Complexity : O(n) Here, n is length of string.

My Personal Notes arrow_drop_up Loves to contribute and help others to learn

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

3

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.