import java.util.Stack;
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack=new Stack<Integer>();
for (int i=0;i<tokens.length;i++){
try{//这里用捕捉异常的方式来处理非Int类型的符号,并单独处理,结构巧妙
int num=Integer.parseInt(tokens[i]);
stack.push(num);
}
catch(Exception e){
int b=stack.pop();
int a=stack.pop();
stack.push(get(a,b,tokens[i]));
}
}
return stack.peek();
}
private int get(int a,int b,String operate){//利用switch,case选择分支结构完成四则运算
switch(operate){
case "+":
return a+b;
case"-":
return a-b;
case "*":
return a*b;
case "/":
return a/b;
default:
return 0;
}
}
}
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are+,-,*,/. Each operand may be an integer or another expression.
Some examples:
算法的思想就是,遍历数据,非符号压入堆栈,运算符就pop前两个整数,运算结束把结果放回堆栈。最终栈顶元素就是结果。