BOJ 17608 막대기

less than 1 minute read

  1. 변수

    (int) N : 주어지는 막대기 개수

    (Stack) st : 막대기 높이를 담고있는 stack

  2. 구현 로직

    • 막대기의 높이를 입력받을때마다

      1. 이전 막대기의 높이 <= 현재 막대기의 높이

        st.pop() // 이전 막대기 pop

        st.push() // 현재 막대기의 높이 push

      2. 이전 막대기의 높이 > 현재 막대기의 높이

        st.push()

      3. 출력

        st.size()

  3. 소스코드

    package baekjoon.Bronze;
       
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.util.Stack;
       
    public class BOJ_17608_막대기 {
    	public static void main(String[] args) throws Exception {
    		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    		int N = Integer.parseInt(br.readLine()); //
    		Stack<Integer> st = new Stack<Integer>();
    		int firstNum = Integer.parseInt(br.readLine());
    		st.push(firstNum);
       
    		for (int i = 0; i < N - 1; i++) {
    			int curNum = Integer.parseInt(br.readLine());
    			if (st.peek() <= curNum) {
    				while (!st.isEmpty()) {
    					if (st.peek() > curNum)
    						break;
    					st.pop();
    				}
    			}
    			st.push(curNum);
    		}
       
    		System.out.println(st.size());
    	}
    }
    
  4. 느낀점

    스택을 pop 했을 때 바로 직전 높이만 peek해서 비교하면 안되고 스택이 빌때까지(while) 그 앞에 있는 모든 높이들을 비교해보면서 pop해줘야 한다! + (break)

    while (!st.isEmpty()) {
    					if (st.peek() > curNum)
    						break;
    					st.pop();
    				}
    

Leave a comment