leetcode227 基本计算器

时间:2019-06-12
本文章向大家介绍leetcode227 基本计算器,主要包括leetcode227 基本计算器使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1先利用符号栈转化为逆波兰表达式,并添加‘,’作为一个数字的结尾;

2然后利用数字栈计算逆波兰表达式的值;

class Solution {
public:
    int calculate(string s_mid) {
        unordered_map<char,int> m={{'+',1},{'-',1},{'*',2},{'/',2}};
        stack<char> s;
        string s_re;
        
        //转逆波兰表达式
        for(int i=0;i<s_mid.size();i++){
            char c=s_mid[i];
            if(c==' ') continue; 
            if(c<='9' && c>='0'){
                while(i<s_mid.size() && s_mid[i]<='9'&&s_mid[i]>='0'){
                    c=s_mid[i];
                    s_re.push_back(c);
                    i++;
                }
                s_re.push_back(',');
                i--;
                continue;
            }
            if(s.empty()){
                s.push(c);
            }else{
                while(!s.empty() && m[s.top()]>=m[c]){
                    s_re.push_back(s.top());
                    s.pop();
                }
                s.push(c);
            }
        }
        while(!s.empty()){
            s_re.push_back(s.top());
            s.pop();
        }
        
        //cout<<s_re<<endl;//输出逆波兰表达式
        //逆波兰表达式求值;
        stack<int> res;
        for(int i=0;i<s_re.size();i++){
            char c=s_re[i];
            if(c==' ') continue;
            if(c<='9' && c>='0'){
                int num=0;
                while(i<s_re.size() && s_re[i]!=','){
                    c=s_re[i];
                    num=num*10+(c-'0');
                    i++;
                }
                res.push(num);
                continue;
            }
            
            int a,b,sum=0;
            b=res.top();res.pop();
            a=res.top();res.pop();
            if(c=='+') 
                sum=a+b;
            else if(c=='-')
                sum=a-b;
            else if(c=='*')
                sum=a*b;
            else if(c=='/')
                sum=a/b;
            res.push(sum);
        }
        return res.top();
    }
};

原文地址:https://www.cnblogs.com/joelwang/p/11013256.html