[LintCode] Expression Evaluation

The idea is straightforward, by using two stacks, we solve this question with O(n) time and O(n) memory.

Note: giving each operator a “rank” makes problem easier to be solved!!^o^

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> op;
        for(string s : expression){
            if(isOperator(s)){
                if(s == "("){
                    op.push(s);
                }else if (s == ")"){
                    while (op.top() != "("){
                        calculate(op,nums);
                    }
                    op.pop();
                }else{
                    while(!op.empty() && order(s) <= order(op.top())){
                        calculate(op,nums);
                    }
                    op.push(s);
                }
            }else nums.push(stoi(s));
        }
        while(!op.empty()){
            calculate(op,nums);
        }
        return nums.empty() ? 0 : nums.top();
    }
    bool isOperator(string s){
        if(s == "+" || s=="-" || s == "*" || s=="/" || s=="(" || s == ")")
            return true;
        else return false;
    }
    int order(string s){
        if(s=="+" || s=="-") return 1;
        else if(s=="*" || s=="/") return 2;
        else return 0;
    }
    void calculate(stack<string>& op, stack<int>& nums){
        int b = nums.top();
        nums.pop();
        int a = nums.top();
        nums.pop();
        string curop = op.top();
        op.pop();
        if(curop == "+")  nums.push(a+b);
        else if(curop == "-")  nums.push(a-b);
        else if(curop == "*")  nums.push(a*b);
        else if(curop == "/")  nums.push(a/b);
    }
};

PS: there is another more complex question: http://www.geeksforgeeks.org/expression-evaluation/

你可能感兴趣的:(lintcode)