7-20 表达式转换 (25 分)

题目链接

#include<iostream>
#include<stack>
#include<unordered_map>
using namespace std;
stack<char> tmp;
unordered_map<char,int> op{
    {'+',1},{'-',1},{'*',2},{'/',2}
};
//-2+3*(-7+-4)+8/+4
bool isNum(const string &str,int &i){//运算数前有正负号,小数,整数 
	if(isdigit(str[i])) return true;
	else if(!isdigit(str[i-1]) && str[i-1]!=')' && isdigit(str[i+1]) && (str[i] == '-' || str[i] == '+')){
		 return true;
	}
	return false;
}
void transfromNum(string &ans,int &i,const string &str){
	if(str[i] == '-') ans += str[i++];
	else if(str[i] == '+') i++;
	while(i < str.length() && (isdigit(str[i]) || str[i] == '.')){
        ans += str[i++];
	}
}
int main(){
    string str,ans;
    cin>>str;
    ans = ":";
    for(int i = 0; i < str.length(); i++){
        if(isNum(str,i)){
			transfromNum(ans,i,str);
			ans += ' ';
			i--;
            continue;
		}else if(str[i] == '('){
            tmp.push(str[i]);
        }else if(str[i] == ')'){
            while(tmp.size() && tmp.top()!='('){
                ans += tmp.top();
                ans += ' ';
                tmp.pop();
            }
            tmp.pop();
        }else {
            while(tmp.size() && op[str[i]] <= op[tmp.top()]){
            	ans += tmp.top();
            	ans += ' ';
                tmp.pop();
            }
            tmp.push(str[i]);
        }
    }
    while(tmp.size()){
    	ans += tmp.top();
    	ans += ' ';
    	tmp.pop();
	}
    for(int i = 1; i < ans.size()-1; i++){
    	cout<<ans[i];
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值