[LeetCode]Evaluate Reverse Polish Notation

Question:

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
思路:新建一个stack,然后遍历表达式,如果是数字就入栈,如果是操作符,就从栈中取出栈顶的两个数字(并pop())进行计算,然后将计算结果入栈。最后栈内剩余的最后一个数字就是需要return的结果。

另外也可以用表达式树实现,由后序遍历转换成中序遍历。

Answer:

class Solution {
public:
    int evalRPN(vector &tokens) {
        stack result;
        for (vector::iterator it = tokens.begin(); it != tokens.end(); it++)
        {
            if (*it == "+" || *it == "-" || *it == "*" || *it == "/")
            {
                int temp1 = result.top(); result.pop();
                int temp2 = result.top(); result.pop();
                result.push( compute(temp1, temp2, *it) );
            }
            else
            {
                result.push(stoi(*it));
            }
        }
        return result.top();
    }
    int compute(int temp1, int temp2, string opt)
    {
        if(opt == "+") return temp2 + temp1;
        else if(opt == "-") return temp2 - temp1;
        else if(opt == "*") return temp2 * temp1;
        else return temp2 / temp1;
    }
    
};


你可能感兴趣的:(算法C++描述,LeetCode,Excercise,C++,语言)