题目:
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解题:
这题是栈的一个经典应用,也比较简单,思路就是:遇到数字就进栈,遇到运算符号就出栈两个数字然后再将计算结果进栈。
代码:
import java.util.Stack;
public class LeetCode150_EvaluateReversePolishNotation {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] s={"4","-2","/","2","-3","-","-"};
System.out.println(evalRPN(s));
}
public static int evalRPN(String[] tokens) {
int length=tokens.length;
Stack<Integer> stack =new Stack<>();
for(int i=0;i<length;i++)
{
if(!isOperator(tokens[i]))
stack.push(Integer.parseInt(tokens[i]));
else {
int operaNum2=stack.pop();
int operaNum1=stack.pop();
if(tokens[i].equals("+"))
stack.push(operaNum1+operaNum2);
else if(tokens[i].equals("-"))
stack.push(operaNum1-operaNum2);
else if(tokens[i].equals("*"))
stack.push(operaNum1*operaNum2);
else {
stack.push(operaNum1/operaNum2);
}
}
}
return stack.pop();
}
public static boolean isOperator(String s)
{
if(s.equals("+")||s.equals("-")||s.equals("*")||s.equals("/"))
return true;
else
return false;
}
}