[프로그래머스] 카드 뭉치

AI·2025년 9월 8일

https://school.programmers.co.kr/learn/courses/30/lessons/159994

class Solution {
    public String solution(String[] cards1, String[] cards2, String[] goal) {

        // goal의 현재 인덱스가 c1,c2의 현재 값과 동일하면 계속 추가
        // 끝까지가면 yes, 안되면 no
        int c1I = 0; int c2I = 0;
        for(int i = 0;i<goal.length;i++){
            if(c1I<cards1.length && goal[i].equals(cards1[c1I])){
                c1I++;
            } else if(c2I<cards2.length && goal[i].equals(cards2[c2I])){
                c2I++;
            } else{
                return "No";
            }
        }
        return "Yes";
    }
}

==

import java.util.ArrayDeque;
import java.util.Arrays;
public class Solution {
    public String solution(String[] cards1, String[] cards2, String[] goal) {
        
        ArrayDeque<String> cardsDeque1 = new ArrayDeque<>(Arrays.asList(cards1));
        ArrayDeque<String> cardsDeque2 = new ArrayDeque<>(Arrays.asList(cards2));
        ArrayDeque<String> goalDeque = new ArrayDeque<>(Arrays.asList(goal));
        
        while(! goalDeque.isEmpty() ) {
            
            if( ! cardsDeque1.isEmpty() && cardsDeque1.peekFirst().equals(goalDeque.peekFirst())) {
                cardsDeque1.pollFirst();
                goalDeque.pollFirst();
            } else if( ! cardsDeque2.isEmpty() && cardsDeque2.peekFirst().equals(goalDeque.peekFirst())) {
                cardsDeque2.pollFirst();
                goalDeque.pollFirst();
            }else {
                break;
            }
        }
        
        return goalDeque.isEmpty() ? "Yes" : "No";
    }
}

==

public class Solution {
    public String solution(String[] cards1, String[] cards2, String[] goal) {
        
        int idx1 = 0;
        int idx2 = 0;
        int idxG = 0;
        
        while( true ) {
            
            if( idxG == goal.length ) return "Yes"; // 이전단계에서 모든 goal 의 단어를 소화
            
            // 현재 따질 goal 의 단어
            String curr = goal[idxG];
            
            if( idx1 <= cards1.length - 1 && curr.equals(cards1[idx1])) {
                idxG++;
                idx1++;
            }else if( idx2 <= cards2.length - 1 && curr.equals(cards2[idx2])) {
                idxG++;
                idx2++;
            }else {
                return "No";
            }
        }
    }
}

0개의 댓글