# Remove brackets from an algebraic string/expression | faceprep

Let us consider the below problem to remove brackets from an algebraic string.

In a mathematics class, Jason the mathematics teacher asked to solve a book of expressions consisting of characters, operators, and brackets. But Jason wants to give simplified expressions by removing brackets from the expressions. Write an algorithm to help Jason simplify an expression by removing brackets

Input: Consists of a string expression, representing an expression.

Output: Return a string representing the simplified expressions by removing brackets

## Algorithm to remove brackets from an algebraic string

The algorithm/logic behind this question is to remove ‘(‘  and ‘)’ from the input string.

1) Get the input.
2) Traverse the string
3) Two methods can be implemented.

• Create a new string variable.
• Copy each element of the input string to the new string.
• If anyone of the parenthesis is encountered as an element, don’t copy that to the new string.

OR

• If anyone of the parenthesis is encountered as an element, replace it with “” (empty space). This method is very easy in Java and Python.

Test case:

Input: x-(p+q)+(y-a)
Output: x-p+q+y-a

## Program to remove brackets from an algebraic string

// Program to remove brackets from an algebraic string

#include
int main()
{
int i=0,c=0,j=0;
char a[100],b[100];

printf(“\nEnter the string : “);
scanf(“%s”,a);
while(a[i]!=’\0′)
{
if((a[i]=='(‘) && (a[i-1]==’-‘))
{
(c==0)?j=i:j=c;
while(a[i]!=’)’)
{
if(a[i+1]==’+’)
b[j++]=’-‘;
else if(a[i+1]==’-‘)
b[j++]=’+’;
else if(a[i+1]!=’)’)
b[j++]=a[i+1];
i++;
}
c=j+1;
}
else if(a[i]=='(‘ && a[i-1]==’+’)
{
(c==0)?j=i:j=c;
while(a[i]!=’)’)
{
b[j++]=a[i+1];
i++;
}
j–;
c=j+1;
}
else if(a[i]==’)’)
{
i++;
continue;
}
else
{
b[j++]=a[i];
}
i++;
}
b[j]=’\0′;
printf(“%s”,b);
return 0;
}

// Program to remove brackets from an algebraic string

#include<bits/stdc++.h>

using namespace std;
int remove_brackets(char ch)
{
if (ch == ‘(‘ || ch ==’)’)
return 1;
else
return 0;
}
int main()
{
string s;
int j=0;
cout<<“Enter the String:”;
cin>>s;
int len = 0;
while (s[len])
len++;
char t[len];
for(int i=0; i< len; i++)
{
int temp = remove_brackets(s[i]);
if (temp == 0)
{
t[j] += s[i];
j++;
}
}
cout<<t;
return 0;
}

// Program to remove brackets from an algebraic string

import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
System.out.println(“Enter the string…”);
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String result = input.replaceAll(“[()]”, “”);                 // Replacing the brackets with “”
System.out.println(result);
}
}

// Program to remove brackets from an algebraic string

s = input(“Enter the string: “)
brackets = (‘()’)
for x in s:
if x in brackets:
s = s.replace(x, “”)
print(s)

Output: