문제 출처: https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV14nnAaAFACFAYD&categoryId=AV14nnAaAFACFAYD&categoryType=CODE&problemTitle=1223&orderBy=FIRST_REG_DATETIME&selectCodeLang=ALL&select-1=&pageSize=10&pageIndex=1
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class Solution {
public static void main(String[] args) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int problemNum = 1;
for (int i = 0; i < 10; i++) {
StringBuilder sb = new StringBuilder();
int size = Integer.parseInt(reader.readLine());
char[] temp = reader.readLine().toCharArray();
Stack<Character> stack = new Stack<>();
char operator = ' ';
for (int j = 0; j < size; j++) {
if (temp[j] == '+' || temp[j] == '*') {
if (!stack.isEmpty()) {
char prev = stack.peek();
if (prev == temp[j]) {
sb.append(stack.pop());
} else if (prev < temp[j]) {
while (!stack.isEmpty()) {
sb.append(stack.pop());
}
}
}
stack.push(temp[j]);
} else {
sb.append(temp[j]);
}
}
while (!stack.isEmpty()) {
sb.append(stack.pop());
}
Stack<Integer> calcStack = new Stack<>();
for (char c : sb.toString().toCharArray()) {
if (c == '+' || c == '*') {
int head = ' ';
int tail = ' ';
int result = 0;
if (!calcStack.isEmpty()) tail = calcStack.pop();
if (!calcStack.isEmpty()) head = calcStack.pop();
if (c == '+') result = head + tail;
else result = head * tail;
calcStack.push(result);
} else {
calcStack.push(c - '0');
}
}
stringBuilder.append("#").append(problemNum++).append(" ");
stringBuilder.append(calcStack.pop()).append("\n");
}
System.out.println(stringBuilder);
}
}
- 문제 접근법이 도저히 생각나지 않아 다른 분들의 로직을 참고하였다.
- 주된 방법은 스택을 사용하는 것이다.

