C++ Detailed Explanation for Removing Extra Brackets

C++ Detailed Explanation for Removing Extra Brackets

topic description

Eliminate redundant parentheses in expressions of four arithmetic operations.
Input a four-arithmetic expression containing parentheses, which may contain redundant parentheses, and program the expression to remove all redundant parentheses. The relative positions of all variables and operation symbols in the original expression remain unchanged, and remain the same as the original expression, etc. price.

input expression output expression
a + ( b + c ) a+(b+c) a+(b+c) a + b + c a+b+c a+b+c
( a × b ) + c ÷ ( d × e ) (a×b)+c÷(d×e) (a×b)+c÷(d×e) a × b + c ÷ ( d × e ) a×b+c÷(d×e) a×b+c÷(d×e)
a + b ÷ ( c − d ) a+b÷(c-d) a+b÷(cd) a + b ÷ ( c − d ) a+b÷(c-d)a+b÷(cd)
a − ( b + c ) a-(b+c) a(b+c) a − ( b + c ) a-(b+c)a(b+c)

Note: When the input is a+b, the output cannot be b+a, that is, the relative position cannot be changed. The expression is input as a string, and the length does not exceed 255. It is not necessary to judge whether the input expression is in the correct format (that is, the program should default that the input expression is in the correct format). All variables are single lowercase letters, as long as all redundant brackets are removed , no simplification of the expression is required.

Input and output samples

input sample

a + ( b + c ) a+(b+c)a+(b+c)

output sample

a + b + c a+b+ca+b+c


Solution & Code

You can use a stack to solve this problem. Traversing the input expression, when encountering the left parenthesis, put its index onto the stack. When a closing parenthesis is encountered, the top element of the stack is popped, indicating the index of the opening parenthesis that matches the closing parenthesis. Then, replace the subexpression between the opening and closing parentheses with the subexpression itself (i.e. remove the parentheses). Finally, output the replaced expression.

So the code is as follows:

#include <bits/stdc++.h>
using namespace std;
int d[128],l;
string s;
stack <int> st;
int main()
{
    
    
	cin >>s; l=s.size();
	d['/']=4; d['*']=3; d['-']=2; d['+']=1;
	for (int i=0;i<l;i++)
	{
    
    
		if (s[i]=='/' || s[i]=='+' || s[i]=='-' || s[i]=='*' || s[i]=='(')
			st.push(i);
		if (s[i]==')')
		{
    
    
			int k;
			for (k=5;s[st.top()]!='(';st.pop())
				k=min(k,d[s[st.top()]]);
			int head=-1,tail=-1;
			if (i+1<l && s[i+1]!=')')
				tail=d[s[i+1]];
			if (st.top()-1>=0 && s[st.top()]!=')')
				head=d[s[st.top()-1]];
			if (k>=tail && k>=head)
				s[i]=s[st.top()]=0;
			if (k==1 && tail==2 && head<=1 || k==3 && tail==4 && head<=3)
				s[i]=s[st.top()]=0;
			st.pop();
		}
	}
	for (int i=0;i<l;i++)
		if (s[i]!=0)
			cout <<s[i];
	return 0;
}

Guess you like

Origin blog.csdn.net/DUXS11/article/details/132063774