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;
}