본문 바로가기
TIL

백준 1874번 : 스택 수열

by 도쿠니 2022. 4. 7.

맞게 푼 것 같고 답도 잘나오는데 자꾸 실패가 떴다.

import java.util.*;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            list.add(sc.nextInt());
        }
        solution(n,list);
    }

    public static void solution(int n, ArrayList<Integer> list) {
        int lCnt = 0;
        int pCnt = 1; // pop한 회수, 절대 n+1만큼 넘어갈 수 없다.
        Stack<Integer> stack = new Stack<>();
        StringBuffer sb = new StringBuffer();
        while (lCnt<n) {
            if (pCnt > n+1) {
                System.out.println("NO");
                return;
            }
            if (!stack.isEmpty() && list.get(lCnt) == stack.peek()) {
                stack.pop();
                sb.append("-\n");
                lCnt++;
                continue;
            }

            stack.push(pCnt++);
            sb.append("+\n");
        }

        System.out.print(sb.toString().trim());
    }
}

한참을 고민하고 질문도 찾아보고 한 결과...

문제점이 있다.

 

list나 stack이나 원시값을 가지고 만든게 아닌 래퍼로 씌어진 객체가 담아져있다.

이러한 값을 == 연산자로 비교하려니까 자꾸 틀리게 나오던 것이였다!

== 비교를 equals로 바꿔서 비교해주니 정답처리되었다..

항상 ==쓸때는 equals로 써야하는 곳인지 원시값인지 아닌지 잘 비교하자. 정 안되겠으면 그냥 다 equals 써라

댓글