【后缀表达式求解】No.3.栈-evaluate-reverse-polish-notation题解(Java版)

牛客网的题目链接

题目描述

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

注意点

可能存在输入值为负数的情况!其余的就按照后缀表达式来计算就OK了!
开两个栈,数字栈满2和字符串栈不为空就进行一次运算,运算出结果后还放回数字栈!
就酱~~
Java语法写蒜法有点头疼,很多数值转换不如C/C++来的方便,多写写习惯了可能就好了.

题解,仅供参考

import java.util.Stack;
public class Solution {
    public int evalRPN(String[] tokens) {
        int ans=0;
        //操作符栈
        Stack<String> op = new Stack<>();
        //数字栈
        Stack<String> num = new Stack<>();
        String opList = "+-*/";

        for(int i=0;i<tokens.length;i++){
            char ch = tokens[i].charAt(0);

            if(tokens[i].length()==1&&opList.indexOf(tokens[i].charAt(0))!=-1){
                op.push(tokens[i]);
            }
            else{
                num.push(tokens[i]);
            }


            //当数字>=2 并且 op栈>=1 时进行计算
            while(op.size()>=1&&num.size()>=2){
                Integer integer1 = new Integer(num.pop());
                Integer integer2 = new Integer(num.pop());

                int index = opList.indexOf(op.pop());
                switch (index){
                    case 0:
                        num.push( String.valueOf(integer1+integer2));
                        break;
                    case 1:
                        num.push( String.valueOf(integer2-integer1));
                        break;
                    case 2:
                        num.push( String.valueOf(integer1*integer2));
                        break;
                    case 3:
                        num.push( String.valueOf(integer2/integer1));
                        break;
                    default:
                        break;
                }
            }
        }
        ans = Integer.valueOf(num.pop());
        return ans;
    }
}