알고리즘/백준

[Java] 백준 1935 - 후위표기식2

E@st 2022. 5. 24. 14:04

문제

풀이

문제를 바로 이해하진 못했지만 이해만 한다면 쉽게 풀 수 있는 문제이다. 후위 표기식은 연산이 뒤에 등장하는 식으로

ABC*+ 라면 ABC*이 A?(B*C)가 된뒤에 +가 오게 되면 A+(B*C) 가되는것이다. 쉽게 말해 문자가 아닌 연산이 오게 되면 앞에 문자 2개를 연산에 의해 계산해주면 된다.

연산이 나오면 최근에 PUSH한 값을 연산해 주는 것이므로 Stack을 사용하면 쉽게 풀 수 있다.

import java.io.*;
import java.util.*;

 class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int cnt = Integer.parseInt(br.readLine());
        String str = br.readLine();
        double[] arr = new double[cnt];
        Stack<Double> stack = new Stack();

        for (int i = 0; i < cnt; i++) {
            arr[i] = Double.parseDouble(br.readLine());
        }

        for (int i = 0; i < str.length(); i++) {
            char temp = str.charAt(i);
            if (temp >= 'A' && 'Z' >= temp) {
                stack.push(arr[temp - 'A']);
            } else {
                if (!stack.empty()) {
                    double num1 = stack.pop();
                    double num2 = stack.pop();
                    switch (str.charAt(i)) {
                        case '*':
                            stack.push(num2*num1);
                            continue;
                        case '/':
                            stack.push(num2/num1);
                            continue;
                        case '+':
                            stack.push(num2+num1);
                            continue;
                        case '-':
                            stack.push(num2-num1);
                            continue;
                    }
                }
            }
        }
        System.out.printf("%.2f",stack.pop());
    }
}