public static int evalRPN(String[] tokens) {
if(tokens.length == 0) {
return 0;
}
int len = tokens.length;
Stack<String> num = new Stack<>();
Stack<String> op = new Stack<>();
for(int i = 0; i < len; i++) {
if(tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals("*") || tokens[i].equals("/")) {
String num1 = num.pop();
String num2 = num.pop();
num.push(operate(num2,tokens[i],num1));
}else {
num.push(tokens[i]);
}
}
return Integer.valueOf(num.pop());
}
public static String operate(String a, String op, String b) {
int result = 0;
switch(op) {
case "+" :
result = Integer.parseInt(a) + Integer.parseInt(b);
break;
case "-" :
result = Integer.parseInt(a) - Integer.parseInt(b);
break;
case "*":
result = Integer.parseInt(a) * Integer.parseInt(b);
break;
case "/":
result = Integer.parseInt(a) / Integer.parseInt(b);
break;
default:
result = 0;
}
return String.valueOf(result);
}
150. Evaluate Reverse Polish Notation
最新推荐文章于 2018-10-12 10:38:02 发布