150. Evaluate Reverse Polish Notation, 자바 풀이

이원석·2023년 9월 1일

Leetcode

목록 보기
11/22

[문제]
You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.

Evaluate the expression. Return an integer that represents the value of the expression.

Note that:

The valid operators are '+', '-', '*', and '/'.
Each operand may be an integer or another expression.
The division between two integers always truncates toward zero.
There will not be any division by zero.
The input represents a valid arithmetic expression in a reverse polish notation.
The answer and all the intermediate calculations can be represented in a 32-bit integer.

https://leetcode.com/problems/evaluate-reverse-polish-notation/?envType=study-plan-v2&envId=top-interview-150


class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();

        for (String t : tokens) {
            int value;

            // 특수기호인 경우
            if (t.equals("+") || t.equals("-") || t.equals("*") || t.equals("/")) {
                char c = t.toCharArray()[0];
                value = c - '0';

                int a = 0;
                int b = 0;

                switch (value) {
                    case -5: // +
                        a = stack.pop();
                        b = stack.pop();
                        stack.push(a + b);
                        break;
                    case -3: // -
                        a = stack.pop();
                        b = stack.pop();
                        stack.push(b - a);
                        break;
                    case -6: // *
                        a = stack.pop();
                        b = stack.pop();
                        stack.push(a * b);
                        break;
                    case -1: // /
                        a = stack.pop();
                        b = stack.pop();
                        stack.push(b / a);
                        break;
                }
            } else { // 숫자인 경우
                value = Integer.parseInt(t);
                stack.push(value);
            }
        }

        // System.out.println('+' - '0');
        // System.out.println('-' - '0');
        // System.out.println('*' - '0');
        // System.out.println('/' - '0');

        return stack.pop();
    }
}

// 2 1 + 3 *
// 숫자가 들어오면 stack에 push
// 연산자가 들어오면 stack에서 pop을 두번하여 연산한 결과를 push

Stack을 활용하여 후위연산자를 구현하는 문제이다.

  1. 숫자가 들어오면 stack에 push
  2. 연산자가 들어오면 stack에서 pop을 두번하여 연산한 결과를 push

0개의 댓글