评估算术表达式在逆波兰表示法中的价值。有效运算符是+,-,*,/。每个操作数可以是整数或另一个表达式。
一些例子:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
方法一 异常处理:
利用异常,判断是否是符号,进而进行计算。
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack=new Stack<>();
for(int i=0;i<tokens.length;i++){
try{
int tem=Integer.parseInt(tokens[i]);
stack.push(tem);
//出现异常,进行计算。
}catch(Exception e){
//注意a和b 的顺序。
int b=stack.pop();
int a=stack.pop();
stack.push(f(a,b,tokens[i]));
}
}
return stack.pop();
}
private int f(int a,int b,String c){
switch(c){
case "+":
return a+b;
case "-":
return a-b;
case "*":
return a*b;
case "/":
return a/b;
default:
return 0;
}
}
方法二 :常规方法
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack=new Stack<>();
for(int i=0;i<tokens.length;i++){
//注意要用equals表达式,不能用==
if(tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals("*") || tokens[i].equals("/")){
int b=stack.pop();
int a=stack.pop();
stack.push(f(a,b,tokens[i]));
}else
stack.push(Integer.parseInt(tokens[i]));
}
return stack.pop();
}
private int f(int a,int b,String c){
switch(c){
case "+":
return a+b;
case "-":
return a-b;
case "*":
return a*b;
case "/":
return a/b;
default:
return 0;
}
}