一道比较好的题,对栈和队列有很大的提高!
给几个测试数据~~
(a-(b-c))
((((a)-(a+b)-((a+b))-(a+b)+a)))
A-((B+C))
答案自己看就知道了!第二个数据很容易错的!
#include <iostream>
#include <cstring>
#include <cstdio>
#include <stack>
using namespace std;
stack<bool> s;
int main()
{
//freopen("a.txt","r",stdin);
char ch[300],src[300],tch[300],aim[300];
int len,i,cnt1,cnt2,k,cas;
bool flag;
cin>>cas;
getchar();
while(cas --)
{
cin.getline(ch,300);
len = strlen(ch);
k = 0;
cnt1 = 0;
cnt2 = 0;
for(i = 0;i < len;i ++)
{
if(ch[i] !=' ') {src[k] = ch[i]; k++;}
}
len = k;
k = 0;
for(i = 0;i < len;i ++)
{
if(i>0&&src[i] == '('&&src[i-1] == '-')
{
tch[k++] = src[i];
flag = 1;
s.push(flag);
continue;
}
if((i>0&&src[i] == '('&&src[i-1] == '+')||(src[i] == '('&&src[i-1]=='(')||(src[i]=='('&&i==0) )
{
flag = 0;
s.push(flag);
continue;
}
if(src[i] == ')')
{
if(!s.empty()) {
flag = s.top();
s.pop();
if(flag == 1) {tch[k++] = ')';}
}
continue;
}
tch[k ++] = src[i];
}
len = k;
k = 0;
for(i = 0;i < len;i ++)
{
if(tch[i] == '('&&tch[i+2] ==')')
continue;
if(tch[i] == ')'&&tch[i-2]=='(')
continue;
aim[k++] = tch[i];
}
for(i = 0;i < k;i ++)
cout<<aim[i];
cout<<endl;
}
return 0;
}