12789번: 도키도키 간식드리미
인하대학교 학생회에서는 중간, 기말고사 때마다 시험 공부에 지친 학우들을 위해 간식을 나눠주는 간식 드리미 행사를 실시한다. 승환이는 시험 기간이 될 때마다 간식을 받을 생각에 두근두
www.acmicpc.net
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Stack<Integer> stack = new Stack<>();
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int count = 1;
for (int i = 0; i < n; i++) {
int currentStudent = Integer.parseInt(st.nextToken());
if (currentStudent == count) {
count++;
while (!stack.isEmpty() && stack.peek() == count) {
stack.pop();
count++;
}
} else {
stack.push(currentStudent);
}
}
while (!stack.isEmpty()) {
if (stack.peek() == count) {
stack.pop();
count++;
} else {
break;
}
}
System.out.println(stack.isEmpty() ? "Nice" : "Sad");
}
}
깨달은 점:
stack.size로 반복할 땐 항상 최신 stack.size 기준으로 반복문이 돌아감
stack.size로 반복할 땐 stack.size를 변동시키는 연산을 하면 원하지 않는 결과가 나올 수 있음.
'Java > AlgorithmPS' 카테고리의 다른 글
프로그래머스) 올바른 괄호 (0) | 2023.10.05 |
---|---|
백준) 균형잡힌 세상 (4949번) (0) | 2023.10.04 |
백준) 괄호 (9012번) (0) | 2023.09.26 |
백준) 좋은 단어(3986번) - 복습 필요 (0) | 2023.09.23 |
백준) 단어 뒤집기2(17413번) (0) | 2023.09.23 |