Skip to content

Latest commit

 

History

History
109 lines (83 loc) · 2.56 KB

150. Evaluate Reverse Polish Notation.md

File metadata and controls

109 lines (83 loc) · 2.56 KB

150. 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.

Note:

  • Division between two integers should truncate toward zero.
  • The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.

Example 1:

Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9

Example 2:

Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6

Example 3:

Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22
Explanation: 
  ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

Solution

从stack里面pop出来的时候,谁是num1谁是num2要注意一下顺序。

java的String没法直接比较是不是数字,除非转成char一个一个比,或者用正则表达。

java里面String的比较,应该用s1.equals(s2)而不是直接s1==s2

java里面set的表达方法:

HashSet<String> operator = new HashSet<String>();
operator.add("+");
if(operator.contains("+"))
	{...}

Code

class Solution {
    public int evalRPN(String[] tokens) {
        int cur = 0;
        int num1 = 0;
        int num2 = 0;
        int num3 = 0;
        HashSet<String> operator = new HashSet<String>();
        operator.add("+");
        operator.add("-");
        operator.add("/");
        operator.add("*");
        
        Stack<Integer> stack = new Stack<Integer>();
        for(String c : tokens)
        {
            if(!operator.contains(c))
                stack.add(Integer.parseInt(c));
            else
            {
                num2 = stack.pop();
                num1 = stack.pop();
                // System.out.println(num1);
                // System.out.println(num2);
                if(c.equals("/"))
                    num3 = num1 / num2;
                else if(c.equals("+"))
                    num3 = num1 + num2;
                else if(c.equals("-"))
                    num3 = num1 - num2;
                else if(c.equals("*"))
                    num3 = num1 * num2;
                stack.add(num3);
                // System.out.println(c);
                // System.out.println(num3);
            }
        }
        return stack.pop();
    }
}