[LintCode] Expression Evaluation

本文介绍了一种通过使用两个栈来解决表达式求值问题的方法,该方法的时间复杂度为O(n),空间复杂度也为O(n)。通过给每个操作符分配等级,使得问题更容易解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值