2. 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个元素进行计算(第一次取出来的是右操作数),然后再把计算结果压栈,依次循环下去,直到栈中剩下一个元素,就是整个表达式的值。

class Solution {
public:
    int evalRPN(vector &tokens) {
        int len = tokens.size();
        if(len == 0)
            return 0;
        if(len == 1)
            return stoi(tokens[0].c_str());
        stack stack;
        for(int i = 0; i < len; ++i)
        {
            if(tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/")
                stack.push(stoi(tokens[i].c_str()));
            else
            {
                int tmp = stack.top();
                stack.pop();
                if(tokens[i] == "+")
                    tmp += stack.top();
                if(tokens[i] == "-")
                    tmp = stack.top() - tmp;
                if(tokens[i] == "*")
                    tmp *= stack.top();
                if(tokens[i] == "/")
                {
                    if(tmp == 0)
                        return 0;
                    tmp = stack.top()/tmp;
                }
                stack.pop();
                stack.push(tmp);
            }
        }
        if(stack.size() == 1)
            return stack.top();
        else
            return 0;
    }
};
stoi(tokens[i].c_str())
/*这里要使用c_str(),因为stoi的参数是const char*,所以在用string时,必须先用c_str()将string转化为char* */

 

你可能感兴趣的:(LeetCode(C++版))