-
Notifications
You must be signed in to change notification settings - Fork 6
Open
Description
문제 풀이
이 문제는 차량 기지 알고리즘을 알고 있다면 쉽게 풀 수 있다.
주어지는 수식을 하나씩 아래 기준으로 나누어 실행하면 된다.
-
알파벳이 나온다면 바로 출력한다.
-
'('가 나온다면 stack에 '('를 추가한다.
-
')'가 나온다면 stack에서 '('가 나오거나 빌 때 까지 pop하여 출력한다.
-
연산자 '*','/'가 나온다면 stack에 연산자를 추가한다.
-
연산자 '+','-'가 나온다면 stack에 연산자를 추가한다. 이 때 stack 안에 '*','/'가 존재한다면 이를 출력한 후 추가한다.
풀이 코드
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
Labels
No labels
