-
[1874] 스택 수열 - Java알고리즘 연습 2022. 2. 22. 13:44
1. 문제
https://www.acmicpc.net/problem/1874
1874번: 스택 수열
1부터 n까지에 수에 대해 차례로 [push, push, push, push, pop, pop, push, push, pop, push, push, pop, pop, pop, pop, pop] 연산을 수행하면 수열 [4, 3, 6, 8, 7, 5, 2, 1]을 얻을 수 있다.
www.acmicpc.net
2. 풀이
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Stack; public class Main { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // 1. Read n, and numbers of target array int n = Integer.parseInt(br.readLine()); int [] target = new int[n]; for(int i = 0; i < n; i++) { target[i] = Integer.parseInt(br.readLine()); } // 2. Use stack to see if they can be pushed in asc order Stack <Integer> stack = new Stack(); StringBuilder sb = new StringBuilder(); int index = 0; int i = 0; while(true) { // a. !isEmpty() && stack.peek() == targetArray[i] : pop while(!stack.isEmpty() && stack.peek() == target[index]) { stack.pop(); sb.append("-").append('\n'); index++; // move to the next number in target array } if(i == n) break; // while loop end conditino // b. push if they finished the first while loop stack.push(++i); sb.append("+").append('\n'); } // 3. If stack !isEmpty() -> "no" if(!stack.isEmpty()) { System.out.println("NO"); } else { System.out.println(sb); } } }
3. 배운점
4. 개선할 점
while문 안에서 수열을 생성할 수 없을 때 바로 "NO"를 출력하고 종료시킬 수 있는 방법을 찾아볼 것
풀이 오류 지적, 다른 접근법 공유, 그 밖에 질문 등 모든 의견을 환영합니다.
'알고리즘 연습' 카테고리의 다른 글
[17087] 숨바꼭질-6 -Java (0) 2022.02.23 [9613] GCD 합 - Java (0) 2022.02.23 [17299] 오등큰수 - Java (0) 2022.02.21 [10866] 덱 - Java (0) 2022.02.17 [10820] 문자열 분석 - Java (0) 2022.02.17