카드 뭉치

하이솝·2026년 3월 6일

소요 시간: 18분 21초
index1, index2가 범위를 넘어서는 오류가 발생했지만 쉽게 발견해서 해결함. 난이도가 낮은 문제라 큰 문제 없이 해결했음

나의 정답

class Solution {
    public String solution(String[] cards1, String[] cards2, String[] goal) {
        String answer = "";
        boolean find = false;
        int index1 = 0; // cards1의 인덱스
        int index2 = 0; // cards2의 인덱스
        for (int i = 0; i < goal.length; i++) {
            find = false;
            if (cards1[index1].equals(goal[i])) {
                find = true;
                index1++;
                if (index1 >= cards1.length) {
                    index1 = cards1.length - 1;
                }
            }
            else if (cards2[index2].equals(goal[i])) { 
                find = true;
                index2++;
                if (index2 >= cards2.length) { 
                    index2 = cards2.length - 1;
                }
            }
            if (find == false) {
                answer = "No";
                break;
            }
        }
        if (find == true) { 
            answer = "Yes";
        }
        return answer;
    }
}

AI 정답
find 변수 사용 없이 훨씬 더 간결한 코드를 만들어냄
if 조건문의 이해도나 활용도가 다소 떨아진다는 생각이 듦

class Solution {
    public String solution(String[] cards1, String[] cards2, String[] goal) {
        int index1 = 0;
        int index2 = 0;
        for (String target : goal) {
            // 1. cards1에서 찾을 수 있는 경우 (인덱스 범위 체크 필수!)
            if (index1 < cards1.length && target.equals(cards1[index1])) {
                index1++;
            } 
            // 2. cards2에서 찾을 수 있는 경우
            else if (index2 < cards2.length && target.equals(cards2[index2])) {
                index2++;
            } 
            // 3. 둘 다 없는 경우 바로 "No" 반환
            else {
                return "No";
            }
        }
        // 끝까지 무사히 통과했다면 "Yes"
        return "Yes";
    }
}

0개의 댓글