leetcode刷题题解——150. 逆波兰表达式求值-爱代码爱编程
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
int result;
for (String token : tokens) {
if (token.length() > 1) {
stack.push(Integer.parseInt(token));
} else {
char c = token.charAt(0);
if (c == '+' || c == '-' || c == '*' || c == '/') {
int a = stack.pop();
int b = stack.pop();
if (c == '+') stack.push(a + b);
if (c == '-') stack.push(b - a);
if (c == '*') stack.push(a * b);
if (c == '/') stack.push(b / a);
} else {
stack.push(Integer.parseInt(token));
}
}
}
result = stack.pop();
return result;
}
这道题思路其实比较简单,就是用栈把要运算的数字进行保存,还有一个点就是用String数组保存表达式,我想之所以使用String,是因为题目给出来的数值范围是-200到200,char类型存储不了这些数值,所以用String存储就说得通了。
还有就是我还判断了String的长度,是因为运算符不能使用Integer.parseInt()方法,如果不判断的话就会导致异常。