• 去除多余括号


    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;
    }
    
    
  • 相关阅读:
    OD 实验(十三)
    第一个 Windows 界面程序
    C 语言
    C 语言
    OD 实验(十二)
    PowerShell 常用命令
    OD 实验(十一)
    OD 实验(十)
    redis
    memcached缓存系统
  • 原文地址:https://www.cnblogs.com/SammyLan/p/1894577.html
Copyright © 2020-2023  润新知