LeetCode—Evaluate Reverse Polish Notation解题报告

来源:互联网 发布:inspiration软件下载 编辑:程序博客网 时间:2024/05/24 06:28

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

原题如下:


题目解析:

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

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

题目的代码如下:

//计算算术表达式的值//作者:张海波//时间:2013-12-16class 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
原创粉丝点击