思路如下:
考虑采用栈进行求解
class Solution {
public int evalRPN(String[] tokens) {
Stack<String> stack=new Stack<>();
for(int i=0;i<tokens.length;i++){
//加法
if(tokens[i]=="+"){
int s1=Integer.parseInt(stack.pop());
int s2=Integer.parseInt(stack.pop());
int res=s1+s2;
stack.push(String.valueOf(res));
}
//减法
else if(tokens[i]=="-"){
int s1=Integer.parseInt(stack.pop());
int s2=Integer.parseInt(stack.pop());
int res=s2-s1;
stack.push(String.valueOf(res));
}
//乘法
else if(tokens[i]=="*"){
int s1=Integer.parseInt(stack.pop());
int s2=Integer.parseInt(stack.pop());
int res=s2*s1;
stack.push(String.valueOf(res));
}
//除法
else if(tokens[i]=="/"){
int s1=Integer.parseInt(stack.pop());
int s2=Integer.parseInt(stack.pop());
int res=s2/s1;
stack.push(String.valueOf(res));
}
//为数字,入栈
else{
stack.push(tokens[i]);
}
}
return Integer.parseInt(stack.pop());
}
}
原题地址:
150. 逆波兰表达式求值