BOJ 1918

문딤·2022년 10월 12일
0

후위 표기식

https://www.acmicpc.net/problem/1918

소스코드

MAIN




    static char[] check = {'+', '-', '*', '/', '(', ')'};


    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        String str = br.readLine();

        Queue<Character>q = new LinkedList<>();

        Stack<Character> MunJa = new Stack<>();

        for (int i = 0; i < str.length(); i++) {

            q.add(str.charAt(i));
        }

        while (!q.isEmpty()) {
            char pop = q.poll();

            if (checkMunja(pop)) {
                sb.append(pop);
            } else {
                //문자열
                if (pop == '(') {
                    MunJa.push(pop);
                } else if (pop == ')') {
                    //')'나올때 까지 문자 뽑기
                    while (!MunJa.isEmpty() && MunJa.peek() != '(') {
                        sb.append(MunJa.pop());
                    }
                    if (!MunJa.isEmpty()) {
                        MunJa.pop();
                    }
                } else {
                    //우선순위 정해서 append
                    while (!MunJa.isEmpty() && priority(MunJa.peek()) >= priority(pop)) {
                        sb.append(MunJa.pop());
                    }
                    MunJa.push(pop);
                }
            }
        }
        while (!MunJa.isEmpty()) {
            sb.append(MunJa.pop());
        }
        System.out.println(sb);
    }

   

연산자 판단

 public static boolean checkMunja(char a) {

        for (int i = 0; i < check.length; i++) {
            if (check[i] == a) {
                return false;
            }
        }
        return true;
        //연산자가 아니니깐
    }

우선순위

  public static int priority(char op) {
        if (op == '*' || op == '/') return 2;
        else if (op == '+' || op == '-') return 1;
        else return 0;
    }

풀이생각

  1. 문자열과 숫자 구분
  2. 괄호에서 연산자를 어떻게 구분해서 출력할지

참고

https://velog.io/@yanghl98/%EB%B0%B1%EC%A4%80-1918-%ED%9B%84%EC%9C%84-%ED%91%9C%EA%B8%B0%EC%8B%9D-JAVA%EC%9E%90%EB%B0%94

profile
풀스택개발자가 될래요

0개의 댓글