题目:
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
比较简单:
public class Solution {
public int evalRPN(String[] tokens) {
Deque<String> stack = new LinkedList<>();
for(int i=0 ; i< tokens.length; ++i)
{
if(!isOperator(tokens[i]))
{
stack.addFirst(tokens[i]);
}
else{
int x= Integer.parseInt(stack.removeFirst());
int y=Integer.parseInt(stack.removeFirst());
if(tokens[i].equals("+")) y=x+y;
else if(tokens[i].equals("-")) y=y-x;
else if(tokens[i].equals("*")) y=y*x;
else y=y/x;
stack.addFirst(String.valueOf(y));
}
}
return Integer.parseInt(stack.peekFirst());
}
public boolean isOperator(String c)
{
return c.equals("+") || c.equals("-") || c.equals("*") || c.equals("/");
}
}