A - Parenthesis UVALive - 4882
题目链接
Sample Input
x
(x+(y+z))
(x+(yz))
(x+y(x+t))
x+y+xt
Sample Output
x
x+y+z
x+yz
x+y(x+t)
x+y+xt
解题思路:删除多余括号问题,用栈解决,遇见左括号进栈(栈里记录的是左括号的在字符串里的位置),遇见右括号考虑右括号右边是加号或者右括号,并且与其对应的左括号左边是加号或者左括号,这种情况是可以去掉括号的。如果右括号右边是字母或者左括号左面是字母则不能去掉(乘法情况)。其中还要考虑左括号左边是右括号的这种情况例如(xy)(xy).
#include<iostream>
#include<stdlib.h>
#include<string.h>
#include<stack>
#include<string>
using namespace std;
stack<int>st;///栈放的是左括号的位置
string s;
int n;
int check(int l,int r)
{
int cnt = 0;
for(int i=l;i<=r;i++)
{
if(s[i] == '(')
++cnt;
else if(s[i]==')')
--cnt;
else if(s[i]=='+'&&cnt == 0)//若(x+y)(xy)则前面的括号不能去
return 0;
}
return 1;
}
int main()
{
int j;
while(cin>>s)
{
while(1)
{
int flag = 0;
int n = s.length();
while(!st.empty())
st.pop();
for(j=0;j<n;j++)
{
if(s[j] == '(')
st.push(j);
else if(s[j] == ')')
{
int x = st.top();
st.pop();
if((x==0||s[x-1]=='+'||s[x-1]=='(')&&(j==n-1||s[j+1]=='+'||s[j+1]==')'))
{
s.erase(x,1);
s.erase(j-1,1);
flag = 1;
break;
}
else if(check(x+1,j-1))//判断(xy)(xy)的这种情况
{
s.erase(x,1);
s.erase(j-1,1);
flag = 1;
break;
}
}
}
if(flag == 0) break;
}
cout<<s<<endl;
}
return 0;
}