注意点:
1.减法和除法都是减(除)数先入栈,被减(除)数后入栈,因此是op2-(/)op1
代码块 import java.util.*; public class Solution { /** * * @param tokens string字符串一维数组 * @return int整型 */ public int evalRPN (String[] tokens) { // write code here Stack <Integer> str = new Stack<Integer>(); int sum; int op1 = 0; int op2 = 0; for(int i = 0; i < tokens.length; i++){ switch(tokens[i]){ case "+": op1 = str.pop(); op2 = str.pop(); str.push(op1+op2); break; case "-": op1 = str.pop(); op2 = str.pop(); str.push(op2-op1); break; case "*": op1 = str.pop(); op2 = str.pop(); str.push(op1*op2); break; case "/": op1 = str.pop(); op2 = str.pop(); str.push(op2/op1); break; default: str.push(Integer.parseInt(tokens[i])); } } return str.peek(); } }