import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param tokens string字符串一维数组 * @return int整型 */ public int evalRPN (String[] tokens) { // write code here Stack<Integer> stack = new Stack<>(); String cur; int a; int b; for(int i = 0; i < tokens.length; i++){ cur = tokens[i]; if((cur.charAt(0)>='0'&&cur.charAt(0)<='9')||cur.length()>1){ //若在0-9,说明是正数,长度大于零避免了负数的问题,满足条件说明是数字,入栈。 stack.push(Integer.parseInt(cur)); }else{ //栈顶元素是运算中的第二个数。 b = stack.pop(); a = stack.pop(); switch(cur){ case "+": stack.push(add(a,b)); break; case "-": stack.push(minus(a,b)); break; case "*": stack.push(mult(a,b)); break; case "/": stack.push(divide(a,b)); break; } } } return stack.peek(); } public int add(int a, int b){ return a+b; } public int minus(int a, int b){ return a-b; } public int mult(int a, int b){ return a*b; } public int divide(int a, int b){ return a/b; } }