Skip to content

[Java] 1918번 후위 표기식 #11

@peppermintt0504

Description

@peppermintt0504

블로그 풀이

문제 풀이

이 문제는 차량 기지 알고리즘을 알고 있다면 쉽게 풀 수 있다.

차량기지 알고리즘 - 위키백과, 우리 모두의 백과사전

주어지는 수식을 하나씩 아래 기준으로 나누어 실행하면 된다.

  1. 알파벳이 나온다면 바로 출력한다.

  2. '('가 나온다면 stack에 '('를 추가한다.

  3. ')'가 나온다면 stack에서 '('가 나오거나 빌 때 까지 pop하여 출력한다.

  4. 연산자 '*','/'가 나온다면 stack에 연산자를 추가한다.

  5. 연산자 '+','-'가 나온다면 stack에 연산자를 추가한다. 이 때 stack 안에 '*','/'가 존재한다면 이를 출력한 후 추가한다.

image

풀이 코드

import java.io.*;
import java.util.*;
 
public class Main {
	public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	public static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

	public static Character[] oper1 = {'+','-'};
	public static Character[] oper2 = {'*','/'};
	public static Character[] bracket = {'(',')'};
	
	public static void main(String[] args) throws IOException {
		String str = br.readLine();
		
		
		
		Stack<Character> stack = new Stack<>();
		
		
		for(int i = 0 ; i < str.length(); i++) {
			char c = str.charAt(i);
			
			if('A' <= c && c <= 'Z') {
				bw.write(c);
			}else if(c == '(') {
				stack.add(c);
			}else if(c == ')') {
				while(!stack.isEmpty()) {
					char temp = stack.pop();
					if(temp == '(') {
						break;
					}
					bw.write(temp);
				}
				
			}else {
				while(!stack.isEmpty() && priority(stack.peek()) >= priority(c)) {
	    			bw.write(stack.pop());
	    		}
	    		stack.add(c);
			}
		}
		while(!stack.isEmpty()) {
			bw.write(stack.pop());
	    }

		
		bw.flush();
		bw.close();
	}
	
	static int priority(char temp) {
		if(Arrays.asList(bracket).contains(temp)) return 0;
		else if(Arrays.asList(oper1).contains(temp)) return 1;
		else return 2;
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions