原题链接在这里:https://leetcode.com/problems/evaluate-reverse-polish-notation/
题目:
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, 遇到数字就压栈,遇到运算符就先pop() op2, 再pop() op1, 按op1 运算符op2 计算,得出结果压回栈,最后站内剩下的就是结果.
Time Complexity: O(n). n = tokens.length.
Space: O(n).
AC Java:
1 class Solution { 2 public int evalRPN(String[] tokens) { 3 if(tokens == null || tokens.length == 0){ 4 return 0; 5 } 6 7 Stack<Integer> stk = new Stack<Integer>(); 8 for(int i = 0; i<tokens.length; i++){ 9 if(tokens[i].equals("+")){ 10 int op2 = stk.pop(); 11 int op1 = stk.pop(); 12 stk.push(op1+op2); 13 }else if(tokens[i].equals("-")){ 14 int op2 = stk.pop(); 15 int op1 = stk.pop(); 16 stk.push(op1-op2); 17 }else if(tokens[i].equals("*")){ 18 int op2 = stk.pop(); 19 int op1 = stk.pop(); 20 stk.push(op1*op2); 21 }else if(tokens[i].equals("/")){ 22 int op2 = stk.pop(); 23 int op1 = stk.pop(); 24 stk.push(op1/op2); 25 }else{ 26 stk.push(Integer.valueOf(tokens[i])); 27 } 28 } 29 30 return stk.pop(); 31 } 32 }