剑指 Offer II 036. 后缀表达式
···
class Solution {
public int evalRPN(String[] tokens) {
// 栈的思路
ArrayDeque<Integer> stack=new ArrayDeque<>();
int i=0;
while(i<tokens.length){
if(!isNumber(tokens[i])){
int b=stack.pollFirst();
int a=stack.pollFirst();
int tmp=calculate( a, b,tokens[i]);
// System.out.println(tmp);
stack.addFirst(tmp);
}else{
stack.addFirst(Integer.parseInt(tokens[i]));
}
i++;
}
return stack.poll();
}
public boolean isNumber(String token) {
return !("+".equals(token) || "-".equals(token) || "*".equals(token) || "/".equals(token));
}
public int calculate(int a,int b,String str){
if(str.equals("+")){
return a+b;
}
if(str.equals("-")){
return a-b;
}
if(str.equals("*")){
return a*b;
}
if(str.equals("/")){
return a/b;
}
return 0;
}
}
···
网友评论