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

cpp
class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> stack;
        if (tokens.empty())
            return 0;
        int len = tokens.size();
        int a, b;
        for (int i = 0; i < len; i++) {
            string s = tokens[i];

            if (s == "+") {
                a = stack.top();
                stack.pop();
                b = stack.top();
                stack.pop();
                stack.push(a + b);
            } else if (s == "-") {
                a = stack.top();
                stack.pop();
                b = stack.top();
                stack.pop();
                stack.push(b - a);
            } else if (s == "*") {
                a = stack.top();
                stack.pop();
                b = stack.top();
                stack.pop();
                stack.push(a * b);
            } else if (s == "/") {
                a = stack.top();
                stack.pop();
                b = stack.top();
                stack.pop();
                stack.push(b / a);
            } else {
                stack.push(atoi(s.c_str()));
            }

        }
        return stack.top();
    }
};

java:

public class Solution {
    public int evalRPN(String[] tokens) {
        String operators = "+-*/";
        Stack<String> stack = new Stack<String>();
        for (String s : tokens) {
            if (!operators.contains(s)) {
                stack.push(s);
            } else {
                int a = Integer.valueOf(stack.pop());
                int b = Integer.valueOf(stack.pop());
                int index = operators.indexOf(s);
                switch (index) {
                    case 0: {
                        stack.push(String.valueOf(a + b));
                        break;
                    }
                    case 1: {
                        stack.push(String.valueOf(b - a));
                        break;
                    }
                    case 2: {
                        stack.push(String.valueOf(a * b));
                        break;
                    }
                    case 3: {
                        stack.push(String.valueOf(b / a));
                        break;
                    }
                }
            }
        }
        return Integer.valueOf(stack.pop());
    }
};
 
原文地址:https://www.cnblogs.com/wxquare/p/5213466.html