import java.util.Stack;
public class Solution {
public int evalRPN(String[] tokens) {
if(tokens == null || tokens.length == 0) return 0;
Stack<Integer> s = new Stack<>();
for (int i = 0; i < tokens.length; i++) {
String cur = tokens[i];
if(cur.equals("+") || cur.equals("-") || cur.equals("*") || cur.equals("/")) {
if(s.size() < 2) return 0;//如果操作数不合法,没有足够的数来操作,返回0
int after = s.pop();
int before = s.pop();
if(cur.equals("+")) {
s.push(before + after);
}else if(cur.equals("-")) {
s.push(before - after);
}else if(cur.equals("*")) {
s.push(before * after);
}else if(cur.equals("/")) {
s.push(before / after);
}
} else {//不是操作数
try {
int num = Integer.parseInt(cur);// 非法字符返回0
s.push(num);
} catch (NumberFormatException e) {
return 0;
}
}
}
return s.size() == 1 ? s.pop() : 0;//结果要合法
public class Solution {
public int evalRPN(String[] tokens) {
if(tokens == null || tokens.length == 0) return 0;
Stack<Integer> s = new Stack<>();
for (int i = 0; i < tokens.length; i++) {
String cur = tokens[i];
if(cur.equals("+") || cur.equals("-") || cur.equals("*") || cur.equals("/")) {
if(s.size() < 2) return 0;//如果操作数不合法,没有足够的数来操作,返回0
int after = s.pop();
int before = s.pop();
if(cur.equals("+")) {
s.push(before + after);
}else if(cur.equals("-")) {
s.push(before - after);
}else if(cur.equals("*")) {
s.push(before * after);
}else if(cur.equals("/")) {
s.push(before / after);
}
} else {//不是操作数
try {
int num = Integer.parseInt(cur);// 非法字符返回0
s.push(num);
} catch (NumberFormatException e) {
return 0;
}
}
}
return s.size() == 1 ? s.pop() : 0;//结果要合法
}
}