去除多余括号

struct OP
{
	int pos;
	char op;
};

char * Remove(char * str)
{
	char * p = str;
	int i = 0;
	stack<OP> ops;
	vector<int> rems;
	while(*p!='\0')
	{
		OP op;
		if(*p=='+'||*p=='-'||*p=='*'||*p=='/'||*p=='(')
		{
			op.op =*p;
			op.pos = i;
			ops.push(op);
		}
		else if(*p==')')
		{
			int next = 0;
			int pre  = 0;
			int lower = 1;
			
			char * t = p+1;
			while(*t!='\0'&&*t==' ')
			{
				++t;
			}
			next = (*t=='*'||*t=='/');

			while(ops.size()>0)
			{
				op = ops.top();
				ops.pop();
				if(op.op=='(')
				{
					break;
				}
				if(op.op=='+'||op.op=='-')
				{
					lower = 0;
				}
			}
			t =&str[op.pos] -1;
			while(t>=str&&*t==' ')
			{
				--t;
			}
			pre = (t>=str&&(*t=='*'||*t=='/'));

			if(lower>=pre&&lower>=next)
			{
				rems.push_back(i);
				rems.push_back(op.pos);
			}
		}
		++i;
		++p;
	}
	if(rems.size()==0)
	{
		return str;
	}
	sort(rems.begin(),rems.end());
	int cur = rems[0];
	int beg = rems[0] +1;
	for(int i = 0;i<rems.size()-1;++i)
	{
		int end = rems[i+1];
		while(beg<end)
		{
			str[cur]=  str[beg];
			++beg;
			++cur;
		}
		beg = end +1;
	}
	while(str[cur]!='\0')
	{
		str[cur]=  str[beg];
		++cur;
		++beg;
	}
	return str;
}

int main()
{
	char str[256]= "(a+b+c+ (d+e) * 8- 5)";
	while(cin>>str)
	{
		
		cout<<Remove(str)<<endl;
	}
	return 0;
}

posted on 2010-12-02 15:46  SammyLan  阅读(506)  评论(0编辑  收藏  举报

导航