import java.util.*;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Solution {
//规律:遇到运算符必进行运算操作
//创建一个栈存储数字,遍历逆波兰式数组,是数字的压入栈,是运算符的则弹栈两个数字进行运算,再将运算结果压会栈中
//遍历完成后栈中只剩一个数为最终的值
public int evalRPN (String[] tokens) {
//?:0或1个 +:1或多个 *:0或多个
Pattern pattern = Pattern.compile("-?[0-9]+.?[0-9]*");
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < tokens.length; i++) {
Matcher m = pattern.matcher(tokens[i]);
if (m.matches()) {
stack.add(Integer.parseInt(tokens[i]));
} else {
stack.add(operation(stack.pop(), stack.pop(), tokens[i]));
}
}
return stack.pop();
}
static int operation(int a, int b, String s) {
switch (s) {
case "+": {
return b + a;
}
case "-": {
return b - a;
}
case "*": {
return b * a;
}
case "/": {
return b / a;
}
default:
throw new IllegalArgumentException("Unexpected value: " + s);
}
}
}