Simplify a given algebraic string of characters, ‘+’, ‘-‘ operators and parentheses. Output the simplified string without parentheses.
Input : "a-(b+c)" Output : "a-b-c" Input : "a-(b-c-(d+e))-f" Output : "a-b+c+d+e-f"
The idea is to check operators just before starting of bracket, i.e., before character ‘(‘. If operator is -, we need to toggle all operators inside the bracket. A stack is used which stores only two integers 0 and 1 to indicate whether to toggle or not.
We iterate for every character of input string. Initially push 0 to stack. Whenever the character is an operator (‘+’ or ‘-‘), check top of stack. If top of stack is 0, append the same operator in the resultant string. If top of stack is 1, append the other operator (if ‘+’ append ‘-‘) in the resultant string.
This article is contributed by Chhavi . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.
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.
- Check if two expressions with brackets are same
- Check for Balanced Brackets in an expression (well-formedness) using Stack
- Remove all duplicate adjacent characters from a string using Stack
- Remove all continuous occurrences of 'a' and all occurrences of 'b'
- Remove repeated digits in a given number
- Smallest string obtained by removing all occurrences of 01 and 11 from Binary String
- Stack | Set 3 (Reverse a string using stack)
- Decode a string recursively encoded as count followed by substring
- Sort string of characters using Stack
- Solve the Logical Expression given by string
- Reduce the string by removing K consecutive identical characters
- Reduce the string to minimum length with the given operation
- Parsing String of symbols to Expression
- Check if a string can be split into even length palindromic substrings
- Lexicographically largest possible String after removal of K characters
- Maximize cost obtained by removal of substrings "pr" or "rp" from a given String
- Reverse words in a given string | Set 2
- Check given string is oddly palindrome or not | Set 2
- Change the given string according to the given conditions
- Java Program to Reverse a String using Stack