[置顶] [LeetCode]150. 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
Subscribe to see which companies asked this question

解决思路:

这个问题可以用栈来解决。我们通过遍历字符串数组,如果是数字,我们就压入栈,如果是”+-*/”,就弹出栈中的两个元素,做运算,最后将结果弹出栈中。

public class Solution {
    public int evalRPN(String[] tokens) {

        int returnValue = 0;
        String operators = "+-*/";
        Stack<String> stack = new Stack<String>();

        for(String t : tokens){
            if(!operators.contains(t)){
                stack.push(t);
            }else{
                int a = Integer.valueOf(stack.pop());
                int b = Integer.valueOf(stack.pop());
                int index = operators.indexOf(t);
                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;
                }
            }
        }
        returnValue = Integer.valueOf(stack.pop());
        return returnValue;

    }
}

你可能感兴趣的:(LeetCode)