Expression Evaluation

Given an expression string array, return the final result of this expression

Example For the expression 2*6-(23+7)/(1+2), input is

[ "2", "*", "6", "-", "(", "23", "+", "7", ")", "/", (", "1", "+", "2", ")" ], return 2

题目本身不难,但是各种情况,什么时候pop,什么时候push需要仔细注意。

class Solution {
public:
    /**
     * @param expression: a vector of strings;
     * @return: an integer
     */
    int evaluateExpression(vector<string> &expression) {
        // write your code here
        stack<int> nums;
        stack<string> ops;

        if(expression.size()<=0)return 0;

        for(int i=0;i<expression.size();i++)
        {
            if(isOp(expression[i]))
            {
                if(expression[i]==")")
                {
                    while(ops.top()!="(")
                    {                    
                        int b=nums.top();nums.pop();
                        int a=nums.top();nums.pop();

                        nums.push(compute(a,b,ops.top()));
                        ops.pop();
                    }
                    ops.pop();
                }
                else if(expression[i]=="(" || ops.empty() ||
                (!ops.empty() && higher(expression[i],ops.top())))
                {
                    ops.push(expression[i]);
                }
                else
                {
                    int b=nums.top();nums.pop();
                    int a=nums.top();nums.pop();

                    nums.push(compute(a,b,ops.top()));
                    ops.pop();

                    ops.push(expression[i]);
                }
            }
            else nums.push(stoi(expression[i]));
        }


                    while(!ops.empty())
                    {                    
                        int b=nums.top();nums.pop();
                        int a=nums.top();nums.pop();

                        nums.push(compute(a,b,ops.top()));
                        ops.pop();
                    }

        return nums.top();
    }

    bool higher(string &a, string &b)
    {
        return ((a=="*" || a=="/") && (b=="+" || b=="-") || b=="(");
    }
    bool isOp(string &a)
    {
        return a=="+" || a=="-" || a=="/" || a=="*" || a=="(" || a==")";
    }

    int compute(int a,int b,string op)
    {
                    if(op=="+")
                    return (a+b);
                    else if(op=="-")
                    return (a-b);
                    else if(op=="*")
                    return (a*b);
                    else if(op=="/")
                    return (a/b);
    }
};

results matching ""

    No results matching ""