[Java] 중위식 -> 후위식

Lee GaEun·2025년 5월 20일

[Java] 알고리즘

목록 보기
77/93
  • 이건 그냥 중위식을 후위식으로 바꾼 건데
  • 이거 생각보다 넘 어려움

import java.io.*;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Scanner;
import java.util.StringTokenizer;

class Solution
{
    public static void main(String args[]) throws Exception
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        //Scanner sc = new Scanner(System.in);
        int T;
        T=10;

        for(int test_case = 1; test_case <= 1; test_case++)
        {
            StringTokenizer st = new StringTokenizer(br.readLine());
            Deque<Character> list = new ArrayDeque<>();
            String postfix = "";
            int N = Integer.parseInt(st.nextToken());

            String a = br.readLine();
            char b;
            char e;
            for(int i=0; i<N; i++) {
                b = a.charAt(i);

                if(b == '(') {
                    list.addLast(b);
                }
                else if (b == ')') {
                    while (!list.isEmpty() && list.peekLast() != '(') {
                        postfix += list.pollLast();
                    }
                    if(!list.isEmpty() && list.peekLast() == '(') list.pollLast();
                }
                else if (b >= '0' && b<='9') {
                    postfix += b;
                    if(!list.isEmpty() && list.peekLast() == '*') {
                        postfix += list.pollLast();
                    }
                }
                else if (b == '+' || b == '*') {
                    while (!list.isEmpty() && precedence(list.peekLast()) >= precedence(b)) {
                        postfix += list.pollLast();
                    }
                    list.addLast(b);
                }
            }
            while (!list.isEmpty()) {
                postfix += list.pollLast();
            }

            System.out.println(postfix);
        }
    }

    private static int precedence(char op) {
        if (op == '*') return 2;
        if (op == '+') return 1;
        return 0;
    }
}
profile
I will give it my all (๑•̀o•́๑)ง

0개의 댓글