Open In App

Remove brackets from an algebraic string containing + and – operators

Last Updated : 14 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Simplify a given algebraic string of characters, ‘+’, ‘-‘ operators and parentheses. Output the simplified string without parentheses.

Examples: 

Input : "(a-(b+c)+d)"
Output : "a-b-c+d"

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. 

Implementation:

C++




// C++ program to simplify algebraic string
#include <bits/stdc++.h>
using namespace std;
 
// Function to simplify the string
char* simplify(string str)
{
    int len = str.length();
 
    // resultant string of max length equal
    // to length of input string
    char* res = new char(len);
    int index = 0, i = 0;
 
    // create empty stack
    stack<int> s;
    s.push(0);
 
    while (i < len) {
          // Don't do any operation
        if(str[i] == '(' && i == 0) {
            i++;
              continue;
        }
       
        if (str[i] == '+') {
 
            // If top is 1, flip the operator
            if (s.top() == 1)
                res[index++] = '-';
 
            // If top is 0, append the same operator
            if (s.top() == 0)
                res[index++] = '+';
 
        } else if (str[i] == '-') {
            if (s.top() == 1) {
                  if(res[index-1] == '+' || res[index-1] == '-') res[index-1] = '+'; // Overriding previous sign
                else res[index++] = '+';
            }
            else if (s.top() == 0) {
                  if(res[index-1] == '+' || res[index-1] == '-') res[index-1] = '-'; // Overriding previous sign
                else res[index++] = '-';
            }
        } else if (str[i] == '(' && i > 0) {
            if (str[i - 1] == '-') {
 
                // x is opposite to the top of stack
                int x = (s.top() == 1) ? 0 : 1;
                s.push(x);
            }
 
            // push value equal to top of the stack
            else if (str[i - 1] == '+')
                s.push(s.top());
        }
 
        // If closing parentheses pop the stack once
        else if (str[i] == ')')
            s.pop();
 
        // copy the character to the result
        else
            res[index++] = str[i];
        i++;
    }
    return res;
}
 
// Driver program
int main()
{
    string s1 = "(a-(b+c)+d)";
    string s2 = "a-(b-c-(d+e))-f";
    cout << simplify(s1) << endl;
    cout << simplify(s2) << endl;
    return 0;
}


Java




// Java program to simplify algebraic string
import java.util.*;
class GfG {
 
// Function to simplify the string
static String simplify(String str)
{
    int len = str.length();
 
    // resultant string of max length equal
    // to length of input string
    char res[] = new char[len];
    int index = 0, i = 0;
 
    // create empty stack
    Stack<Integer> s = new Stack<Integer> ();
    s.push(0);
 
    while (i < len) {
          // Don't do any operation
        if(str.charAt(i) == '(' && i == 0) {
            i++;
              continue;
        }
       
        if (str.charAt(i) == '+') {
 
            // If top is 1, flip the operator
            if (s.peek() == 1)
                res[index++] = '-';
 
            // If top is 0, append the same operator
            if (s.peek() == 0)
                res[index++] = '+';
 
        } else if (str.charAt(i) == '-') {
            if (s.peek() == 1)
                res[index++] = '+';
            else if (s.peek() == 0)
                res[index++] = '-';
        } else if (str.charAt(i) == '(' && i > 0) {
            if (str.charAt(i - 1) == '-') {
 
                // x is opposite to the top of stack
                int x = (s.peek() == 1) ? 0 : 1;
                s.push(x);
            }
 
            // push value equal to top of the stack
            else if (str.charAt(i - 1) == '+')
                s.push(s.peek());
        }
 
        // If closing parentheses pop the stack once
        else if (str.charAt(i) == ')')
            s.pop();
               
        else if(str.charAt(i) == '(' && i == 0)
              i = 0;
        // copy the character to the result
          else
            res[index++] = str.charAt(i);
        i++;
    }
    return new String(res);
}
 
// Driver program
public static void main(String[] args)
{
    String s1 = "(a-(b+c)+d)";
    String s2 = "a-(b-c-(d+e))-f";
    System.out.println(simplify(s1));
    System.out.println(simplify(s2));
}
}


Python3




# Python3 program to simplify algebraic String
 
# Function to simplify the String
 
 
def simplify(Str):
    Len = len(Str)
 
    # resultant String of max Length
    # equal to Length of input String
    res = [None] * Len
    index = 0
    i = 0
 
    # create empty stack
    s = []
    s.append(0)
 
    while (i < Len):
          if (Str[i] == '(' and i == 0):
                i += 1
                continue
 
        if (Str[i] == '+'):
 
            # If top is 1, flip the operator
            if (s[-1] == 1):
                res[index] = '-'
                index += 1
 
            # If top is 0, append the
            # same operator
            if (s[-1] == 0):
                res[index] = '+'
                index += 1
 
        else if (Str[i] == '-'):
            if (s[-1] == 1):
                res[index] = '+'
                index += 1
            else if (s[-1] == 0):
                res[index] = '-'
                index += 1
        else if (Str[i] == '(' and i > 0):
            if (Str[i - 1] == '-'):
 
                # x is opposite to the top of stack
                x = 0 if (s[-1] == 1) else 1
                s.append(x)
 
            # append value equal to top of the stack
            else if (Str[i - 1] == '+'):
                s.append(s[-1])
 
        # If closing parentheses pop
        # the stack once
        else if (Str[i] == ')'):
            s.pop()
 
        # copy the character to the result
        else:
            res[index] = Str[i]
            index += 1
        i += 1
    return res
 
# Driver Code
if __name__ == '__main__':
 
    s1 = "(a-(b+c)+d)"
    s2 = "a-(b-c-(d+e))-f"
    r1 = simplify(s1)
    for i in r1:
        if i != None:
            print(i, end = " ")
        else:
            break
    print()
    r2 = simplify(s2)
    for i in r2:
        if i != None:
            print(i, end = " ")
        else:
            break
 
# This code is contributed by PranchalK


C#




// C# program to simplify algebraic string
using System;
using System.Collections.Generic;
 
class GfG
{
 
// Function to simplify the string
static String simplify(String str)
{
    int len = str.Length;
 
    // resultant string of max length equal
    // to length of input string
    char []res = new char[len];
    int index = 0, i = 0;
 
    // create empty stack
    Stack<int> s = new Stack<int> ();
    s.Push(0);
 
    while (i < len)
    {
          // Don't do any operation
        if(str[i] == '(' && i == 0)
        {
            i++;
              continue;
        }
       
        if (str[i] == '+')
        {
 
            // If top is 1, flip the operator
            if (s.Peek() == 1)
                res[index++] = '-';
 
            // If top is 0, append the same operator
            if (s.Peek() == 0)
                res[index++] = '+';
 
        }
        else if (str[i] == '-')
        {
            if (s.Peek() == 1)
                res[index++] = '+';
            else if (s.Peek() == 0)
                res[index++] = '-';
        }
        else if (str[i] == '(' && i > 0)
        {
            if (str[i - 1] == '-')
            {
 
                // x is opposite to the top of stack
                int x = (s.Peek() == 1) ? 0 : 1;
                s.Push(x);
            }
 
            // push value equal to top of the stack
            else if (str[i - 1] == '+')
                s.Push(s.Peek());
        }
 
        // If closing parentheses pop the stack once
        else if (str[i]== ')')
            s.Pop();
       
        // copy the character to the result
        else
            res[index++] = str[i];
        i++;
    }
    return new String(res);
}
 
// Driver code
public static void Main(String[] args)
{
    String s1 = "(a-(b+c)+d)";
    String s2 = "a-(b-c-(d+e))-f";
    Console.WriteLine(simplify(s1));
    Console.WriteLine(simplify(s2));
}
}
 
// This code has been contributed by 29AjayKumar


Javascript




<script>
// Javascript program to simplify algebraic string
 
// Function to simplify the string
function simplify(str)
{
    let len = str.length;
   
    // resultant string of max length equal
    // to length of input string
    let res = new Array(len);
    let index = 0, i = 0;
   
    // create empty stack
    let s = [];
    s.push(0);
   
    while (i < len) {
        // Don't do any operation
        if(str[i] == '(' && i == 0) {
            i++;
              continue;
        }
             
        if (str[i] == '+') {
   
            // If top is 1, flip the operator
            if (s[s.length-1] == 1)
                res[index++] = '-';
   
            // If top is 0, append the same operator
            if (s[s.length-1] == 0)
                res[index++] = '+';
   
        } else if (str[i] == '-') {
            if (s[s.length-1] == 1)
                res[index++] = '+';
            else if (s[s.length-1] == 0)
                res[index++] = '-';
        } else if (str[i] == '(' && i > 0) {
            if (str[i - 1] == '-') {
   
                // x is opposite to the top of stack
                let x = (s[s.length-1] == 1) ? 0 : 1;
                s.push(x);
            }
   
            // push value equal to top of the stack
            else if (str[i - 1] == '+')
                s.push(s[s.length-1]);
        }
   
        // If closing parentheses pop the stack once
        else if (str[i] == ')')
            s.pop();
             
        // copy the character to the result
        else
            res[index++] = str[i];
        i++;
    }
    return (res).join("");
}
 
// Driver program
let s1 = "(a-(b+c)+d)";
let s2 = "a-(b-c-(d+e))-f";
document.write(simplify(s1)+"<br>");
document.write(simplify(s2)+"<br>");
 
 
// This code is contributed by rag2127
</script>


Output

a-b-c+d
a-b+c+d+e-f

Time Complexity: O(N), Where N is the length of the given string.
Auxiliary Space: O(N)

 



Previous Article
Next Article

Similar Reads

Binary tree to string with brackets
Construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way. The null node needs to be represented by empty parenthesis pair "()". Omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree. Examples: Input : Preorder: [1,
8 min read
Balance a string after removing extra brackets
Given a string of characters with opening and closing brackets. The task is to remove extra brackets from string and balance it. Examples: Input: str = "gau)ra)v(ku(mar(rajput))" Output: gaurav(ku(mar(rajput))) Input: str = "1+5)+5+)6+(5+9)*9" Output: 1+5+5+6+(5+9)*9 Approach: Start traversing from left to right.Check if the element at current inde
6 min read
Find an equal point in a string of brackets
Given a string of brackets, the task is to find an index k which decides the number of opening brackets is equal to the number of closing brackets. The string must be consists of only opening and closing brackets i.e. '(' and ')'. An equal point is an index such that the number of opening brackets before it is equal to the number of closing bracket
14 min read
Lexicographically smallest and largest anagrams of a string containing another string as its substring
Given two strings S1 of size N and S2 of size M, the task is to find the lexicographically smallest and the largest anagrams of S1 such that it contains the string S2 as a substring. Examples: Input: S1 = "hheftaabzzdr", S2 = "earth" Output: abdearthfhzz, zzhfearthdba Explanation: The smallest anagram of the given string S1 with S2 as a substring i
13 min read
Number of closing brackets needed to complete a regular bracket sequence
Given an incomplete bracket sequence S. The task is to find the number of closing brackets ')' needed to make it a regular bracket sequence and print the complete bracket sequence. You are allowed to add the brackets only at the end of the given bracket sequence. If it is not possible to complete the bracket sequence, print "IMPOSSIBLE". Let us def
7 min read
Balanced expressions such that given positions have opening brackets | Set 2
Given an integer n and an array of positions ‘position[]’ (1 &lt;= length(position[]) &lt;= 2n), find the number of ways of proper bracket expressions that can be formed of length 2n such that given positions have the opening bracket. Note: position[] array is given in the form of (1-based indexing) [0, 1, 1, 0]. Here 1 denotes the positions at whi
15+ min read
Print the balanced bracket expression using given brackets
Given four integers a, b, c and d which signifies the number of four types of brackets. "((""()"")(""))" The task is to print any balanced bracket expression using all the given brackets. If we cannot form a balanced bracket expression then print -1. In case of multiple answers, print any one. Examples: Input: a = 3, b = 1, c = 4, d = 3 Output: (((
6 min read
Check if it is possible to obtain a Balanced Parenthesis by shifting brackets to either end at most K times
Given a string S of size N consisting of only '(' and ')' only and a positive integer K, the task is to check if the given string can be made a valid parenthesis sequence by moving any characters of the string S to either end of the string at most K number of times. Examples: Input: S = ")(", K = 1Output: YesExplanation: Move S[0] to the end of the
8 min read
Minimum swaps to balance the given brackets at any index
Given a balanced string of even length consisting of equal number of opening brackets ‘[‘ and closing brackets ‘]’ , Calculate the minimum number of swaps to make string balanced. An unbalanced string can be made balanced by swapping any two brackets. A string is called balanced if it can be represented in the form of "[S1]" where S1 is a balanced
5 min read
Print all Balanced Brackets Strings that can be formed by replacing wild card '?'
Given string str containing characters '?', '(' and ')', the task is to replace the '?' character with '(' or ')' and print all the strings containing balanced brackets Example: Input: str = "????"Output:()()(()) Input: str = "(()?"Output: (()) Approach: The given problem can be solved using recursion and backtracking. The idea is to substitute eve
10 min read
Article Tags :
Practice Tags :