public class Solution {
public int evalRPN(String[] tokens) {
// 栈,用于遍历初始字符串数组
Deque<Integer> stack = new ArrayDeque<Integer>();
int a, b;// 临时存放栈中弹出两个元素
/**
* 遍历初始字符串数组,
* 若当前字符为 运算符 ,则从栈中弹出两个元素,并用该运算符对它们进行运算,然后再将运算结果压入栈
* 若读到的是数字,则直接将其压入栈,不作其他操作
*/
for (int i = 0; i < tokens.length; i++) {
String temp = tokens[i];
switch (temp) {
case "+":
a = stack.pop();
b = stack.pop();
stack.push((b + a));
break;
case "-":
a = stack.pop();
b = stack.pop();
stack.push(b - a);
break;
case "*":
a = stack.pop();
b = stack.pop();
stack.push(b * a);
break;
case "/":
a = stack.pop();
b = stack.pop();
if (a == 0) {
return -1;
}
stack.push(b / a);
break;
default:
stack.push(Integer.parseInt(temp));
}
}
int result = stack.peek();
return result;
}
}
public class Solution {
int index;
public int evalRPN(String[] tokens) {
index = tokens.length - 1;
return recurse(tokens);
}
private int recurse(String[] tokens) {
String word = tokens[index--];
int a, b;
switch (word) {
case "+":
b = recurse(tokens);
a = recurse(tokens);
return a + b;
case "-":
b = recurse(tokens);
a = recurse(tokens);
return a - b;
case "*":
b = recurse(tokens);
a = recurse(tokens);
return a * b;
case "/":
b = recurse(tokens);
a = recurse(tokens);
return a / b;
default:
return Integer.parseInt(word);
}
}
}
public class Solution {
private int calculate (int a, int b, String op) {
switch(op) {
case "+" : return a + b;
case "-" : return a - b;
case "*" : return a * b;
case "/" : return a / b;
default : return 0;
}
}
public int evalRPN(String[] tokens) {
if (tokens == null || tokens.length < 1) return 0;
String operations = "+-*/";
Stack<Integer> stack = new Stack<>();
for (String s : tokens) {
if (operations.contains(s)) {
int second = stack.pop();
int first = stack.pop();
stack.push(calculate(first, second, s));
} else {
stack.push(Integer.valueOf(s));
}
}
return stack.pop();
}
}