解法1:构建一个栈,循环string数组,讲数组中的元素转换成int放入栈中,如果出现了异常,说明是操作符号。然后捕获进行处理,即出栈两个元素进行相应的加减乘除操作。操作后的结果在放入栈中,最终栈中的元素即为最终结果。
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
for(int i = 0;i<tokens.length;i++){
try{
int num = Integer.parseInt(tokens[i]);
stack.add(num);
}catch (Exception e) {
int b = stack.pop();
int a = stack.pop();
stack.add(get(a, b, tokens[i]));
}
}
return stack.pop();
}
private int get(int a,int b,String operator){
switch (operator) {
case "+":
return a+b;
case "-":
return a-b;
case "*":
return a*b;
case "/":
return a/b;
default:
return 0;
}
}
}