表达式的值

给一个用字符串表示的表达式数组,求出这个表达式的值。
表达式只包含整数, +, -, *, /, (, )
static bool cmp[][7] =
{
    {0,0,0,0,0,0,0},
    {1,1,1,0,0,0,1},
    {1,1,1,0,0,0,1},
    {1,1,1,1,1,0,1},
    {1,1,1,1,1,0,1},
    {1,0,0,0,0,0,1},
    {1,0,0,0,0,0,0}
};

static const vector<string> operators = {"#", "+", "-", "*", "/", "(", ")"}; 

int evaluateExpression(vector<string> &expression) {
    
    static unordered_map<string, int> hash;
    
    for (int i = 0; i < operators.size(); ++i) {
        hash[operators[i]] = i;  
    }

    vector<int> optr(1, 0); // expression extended to  "#" expression "#"

    vector<double> oprd;

    expression.push_back("#");
    for (auto e : expression) {
        auto iter = hash.find(e);
        if (iter == hash.end()) {
            oprd.push_back(atoi(e.c_str()));
            continue;
        }
        int idx = iter->second;
        while (true) {
            int prior = optr.back();

            if (!cmp[prior][idx]) {
                optr.push_back(idx);
                break;
            }

            optr.pop_back();

            if (prior == 5) { break; }
           
            double b = oprd.back();
            oprd.pop_back();

            double a = oprd.back();
            oprd.pop_back();

            switch (prior) {
            case 1 :
                oprd.push_back(a + b);
            break;
            case 2 :
                oprd.push_back(a - b);
            break;
            case 3 :
                oprd.push_back(a * b);
            break;
            case 4 :
                oprd.push_back(a / b);
            break;
            }
        }
    }
    return oprd.empty() ? 0 : static_cast<int>(oprd.back());
}
阅读 584

推荐阅读
shiyang6017
用户专栏

计算机

18 人关注
107 篇文章
专栏主页