LeetCode 之 Evaluate Reverse Polish Notation — C++ 实现

来源:互联网 发布:海淘网站farfetch 知乎 编辑:程序博客网 时间:2024/06/06 18:07

Evaluate Reverse Polish Notation

 

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +-*/. Each operand may be an integer or another expression.

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
计算逆波兰式中算术表达式的值。

合法的操作符有+-*/。每个操作数为整数或者另一个表达式。

例如:

 ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
分析:

    顺序扫描,遇见数字压栈,遇见操作符则从栈顶取出两个操作数(注意:先出栈的是第二个操作数),然后计算并将结果再压栈,重复此过程直到计算完毕,最后取出栈顶的元素即为结果值。

注意:下面的代码是假设输入的逆波兰式合法,没有考虑多余的操作符或者操作数不够的情况。可以通过检查栈的是否为空来达到检测的目的。

class Solution {public:    int evalRPN(vector<string>& tokens) {        if(tokens.empty())        {            return 0;        }                int retVal = 0;        bool isoperator = false;        stack<int> tokenStack;        int tokensSize = tokens.size();                for(int index = 0; index < tokensSize; ++index)        {            if(tokens[index] == "+" || tokens[index] == "-" || tokens[index] == "*" || tokens[index] == "/")            {                retVal = tokenStack.top();//如果为操作符,则取栈顶的两个元素参与计算                tokenStack.pop();                switch(tokens[index][0])                {                    case '+':                    {                        retVal += tokenStack.top();                    }                    break;                    case '-':                    {                        retVal = tokenStack.top() - retVal;                    }                    break;                    case '*':                    {                        retVal *= tokenStack.top();                    }                    break;                    case '/':                    {                        retVal = tokenStack.top() / retVal;                    }                    break;                    default:                    break;                }                tokenStack.pop();//删除第二个操作数                tokenStack.push(retVal); //计算结果压栈            }            else //数字,转换后压栈            {                tokenStack.push(atoi(tokens[index].c_str()));            }        }                return tokenStack.top();    }};

0 0
原创粉丝点击