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:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
实现逆波兰算法的关键是查找运算符。
利用栈,将tokens中的元素压入栈,一旦遇到运算符取出两个栈顶元素(取出的同时删除pop())进行运算,将运算所得的结果压入栈内
import java.util.Stack;
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> s=new Stack<Integer>();
for (int i=0;i<tokens.length;i++){
if(tokens[i].equals("+")){
int right=s.pop();
int left=s.pop();
int result=left+right;
s.push(result);
}else if(tokens[i].equals("*")){
int right=s.pop();
int left=s.pop();
int result=left*right;
s.push(result);
}else if(tokens[i].equals("-")){
int right=s.pop();
int left=s.pop();
int result=left-right;
s.push(result);
}else if(tokens[i].equals("/")){
int right=s.pop();
int left=s.pop();
int result=left/right;
s.push(result);
}else{
s.push(Integer.parseInt(tokens[i]));
}
}
return s.pop();
}
}