LeetCode Featured TOP interview questions (Java implementation) - Reverse Polish expression evaluation

One, Title Description

1.1 Topic
  • Reverse Polish expression evaluation

  • According to Reverse Polish Notation, evaluate the expression. The valid operators are +, -, *, /. Each operand can be an integer, it can be another reverse Polish notation.

  • Description:
    integer division retaining only the integer part.
    Given reverse Polish notation always effective. In other words, the effective numerical expression is always obtained and there is no divisor is zero.

  • Example 1:

输入: ["2", "1", "+", "3", "*"]
输出: 9
解释: ((2 + 1) * 3) = 9
  • Example 2:
输入: ["4", "13", "5", "/", "+"]
输出: 6
解释: (4 + (13 / 5)) = 6
  • Example 3:
输入: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
输出: 22
解释: 
  ((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
1.2 knowledge points
  • Stack
1.3 topic Link

Second, problem-solving ideas

2.1 self-development ideas

  The idea is simple question, directly stacks to handle it, to be noted that when the operand from the stack pop, pop-up to a first value of the second operand arithmetic should be in the range, and the second pop value should be in the second operand arithmetic, mainly to solve the number of such subtraction and addition calculation value of the operand location.

Third, the implementation code

3.1 to achieve self-development
class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();

        for(String token : tokens) {
            int ret, fir, sec;
            switch(token){
                case "+":
                    ret = stack.pop() + stack.pop();
                    break;
                case "-":
                    fir = stack.pop();
                    sec = stack.pop();
                    ret = sec - fir;
                    break;
                case "*":
                    ret = stack.pop() * stack.pop();
                    break;
                case "/":
                    fir = stack.pop();
                    sec = stack.pop();
                    ret = sec / fir;
                    break;
                default:
                    ret = Integer.valueOf(token);
                    break;
            }
            stack.push(ret);
        }  
        return stack.pop(); 
    }
}
Published 267 original articles · won praise 32 · views 40000 +

Guess you like

Origin blog.csdn.net/qq_40697071/article/details/104046064