Given two expressions in the form of strings. The task is to compare them and check if they are similar. Expressions consist of lowercase alphabets, ‘+’, ‘-‘ and ‘( )’.
Input : exp1 = "-(a+b+c)" exp2 = "-a-b-c" Output : Yes Input : exp1 = "-(c+b+a)" exp2 = "-c-b-a" Output : Yes Input : exp1 = "a-b-(c-d)" exp2 = "a-b-c-d" Output : No
It may be assumed that there are at most 26 operands from ‘a’ to ‘z’ and every operand appears only once.
A simple idea behind is to keep a record of the Global and Local Sign(+/-) through the expression. The Global Sign here means the multiplicative sign at each operand. The resultant sign for an operand is local sign multiplied by the global sign at that operand.
For example, the expression a+b-(c-d) is evaluated as (+)+a(+)+b(-)+c(-)-d => a + b – c + d. The global sign (represented inside bracket) is multiplied to the local sign for each operand.
In the given solution, stack is used to keep record of the global signs. A count vector records the counts of the operands(lowercase Latin letters here). Two expressions are evaluated in opposite manners and finally, it is checked if the all entries in the count vector are zeros.
This article is contributed by Amol Mejari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Binary tree to string with brackets
- Find an equal point in a string of brackets
- Remove brackets from an algebraic string containing + and - operators
- Balance a string after removing extra brackets
- Printing brackets in Matrix Chain Multiplication Problem
- Number of closing brackets needed to complete a regular bracket sequence
- Evaluation of Prefix Expressions
- Check whether K-th bit is set or not
- Check if the two given stacks are same
- Check whether a given number is even or odd
- Check if the given string is K-periodic
- Check if a triplet with given sum exists in BST
- Check whether a given string is Heterogram or not
- Check if it is possible to transform one string to another
- Check if two trees are Mirror | Set 2
Improved By : sanjeev2552