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.
Input: str = “[[0,&,1],|,[!,1]]”
Input: str = “[!,[[0,&,[!,1]],|,[!,[[!,0],&,1]]]]”
- Start traversing the string from the end.
- 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.
- Perform the respective operations on the vector elements then push the result back into the stack.
- 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:
Time Complexity : O(n) Here, n is length of string.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Parsing String of symbols to Expression
- How to check string is alphanumeric or not using Regular Expression
- Evaluate a boolean expression represented as string
- Check if a binary string has a 0 between 1s or not | Set 2 (Regular Expression Approach)
- Find all the patterns of "1(0+)1" in a given string | SET 2(Regular Expression Approach)
- Check if a string contains only alphabets in Java using Lambda expression
- Check if a given string is a valid number (Integer or Floating Point) in Java | SET 2 (Regular Expression approach)
- Solve the Crossword Puzzle
- How to solve RSA Algorithm Problems?
- Program to solve the Alligation Problem
- Logical and Physical Address in Operating System
- Expression Evaluation
- Arithmetic Expression Evalution
- Balanced expression with replacement
- Expression contains redundant bracket or not
- Evaluate an array expression with numbers, + and -
- How to validate MAC address using Regular Expression
- Stack | Set 4 (Evaluation of Postfix Expression)
- How to validate a domain name using Regular Expression
- Find if an expression has duplicate parenthesis or not