LeetCode—Evaluate Reverse Polish Notation解题报告

转载请注明:http://blog.csdn.net/ict2014/article/details/17351145

原题如下:


题目解析:

      简单明了的一句话就是:求解算术表达式的值。最经典的做法就是使用栈来解决此种问题。对于此道题目,我们使用一个“操作数栈”保存操作数,当遇到“操作符”的时候,就从栈中pop出两个元素,进行计算,然后将结果push至“操作数栈”中,然后继续进行扫描即可。最终“操作数栈”的栈顶就是我们所需要的结果。

      算法的时间复杂度为O(n),空间复杂度最多为O(n/2)。

题目的代码如下:

//计算算术表达式的值
//作者:张海波
//时间:2013-12-16
class Solution {
public:
    //用栈保存操作数,遇到运算符就出栈两个运算数,
    //计算结果,然后将结果压入到栈中
    int evalRPN(vector<string> &tokens) {
        stack<int> operands;
        int tokens_size = tokens.size();
        int result, operand1, operand2;
        for(int i = 0; i < tokens_size; ++i) {
            if(IsOperator(tokens[i])){
                operand1 = operands.top();
                operands.pop();
                operand2 = operands.top();
                operands.pop();
                result = CalculateArithmetic(operand2,tokens[i],operand1);
                operands.push(result);
            }else{
                operands.push(atoi(tokens[i].c_str()));
            }
        }
        
        return operands.top();
    }
    
    //判断字符是否为运算符
    bool IsOperator(const string& ch){
        for(int i = 0; i < 4; ++i){
            if(ch == operators_[i])
                 return true;
        }
        
        return false;
    }
    
    //计算算术表达式的值
    //operand1 _operator operand2
    //例如:2 - 3
    int CalculateArithmetic(const int& operand1,
                            const string& _operator,
                            const int& operand2){
        int result = 0;
        
        if(_operator == operators_[0]){
            result = operand1 + operand2;
        }else if(_operator == operators_[1]){
            result = operand1 - operand2;
        }else if(_operator == operators_[2]){
            result = operand1 * operand2;
        }else if(_operator == operators_[3]){
            result = operand1 / operand2;
        }
        
        return result;
    }
private:
    //运算符
    string operators_[4] = {"+","-","*","/"};
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值