150.逆波兰表达式求值
思路:
后缀转前缀:利用栈,从左向右扫描操作数入栈,从右向左出栈
还要考虑 “-” 和 “-11” 的操作
- 判断字符串长度是否为 1,若为 1,可能是数字或者符号,若不为 1,只有可能是数字
- 若长度为1:若为符号,通过 switch 以及后缀转前缀 求值;若为数字,直接将字符串转为数字入栈
- 若不为1,直接将字符串转为数字入栈
- 此时栈内都是表达式计算过的数字,直接相加即可
代码实现
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
char c;
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].length() == 1) {
c = tokens[i].charAt(0);
if (c == '+' || c == '-' || c == '*' || c == '/') {
int x = stack.pop();
int y = stack.pop();
int res = 0;
switch(c) {
case '+' :
res = y + x;
break;
case '-' :
res = y - x;
break;
case '*' :
res = y * x;
break;
case '/' :
res = y / x;
break;
}
stack.push(res);
}
else {
stack.push(Integer.parseInt(tokens[i]));
}
} else {
stack.push(Integer.parseInt(tokens[i]));
}
}
int sum = 0;
while (!stack.isEmpty()) {
sum += stack.pop();
}
return sum;
}
}