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
Stack应用,遇到数字push,遇到符号pop并计算。
public class Solution { public int evalRPN(String[] tokens) { Stack<Integer> s = new Stack<Integer>(); int opd1 = 0, opd2 = 0; for(String str: tokens){ if(str.equals("+")){ opd1 = s.pop(); opd2 = s.pop(); s.push(opd2 + opd1); } else if(str.equals("-")){ opd1 = s.pop(); opd2 = s.pop(); s.push(opd2 - opd1); } else if(str.equals("*")){ opd1 = s.pop(); opd2 = s.pop(); s.push(opd2 * opd1); } else if(str.equals("/")){ opd1 = s.pop(); opd2 = s.pop(); s.push(opd2 / opd1); } else{ s.push(Integer.parseInt(str)); } } return s.pop(); } }
Advertisements