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

이찬혁·2024년 6월 25일

알고리즘

목록 보기
72/72

프로그래머스 Lv1 - 카드 뭉치 문제

프로그래머스 문제 중 레벨 1 카드 뭉치 문제를 풀이했다.

연습문제로 분류되어있어서 그런지 난이도는 어렵지 않았다.

문제 조건

  • 원하는 카드 뭉치에서 카드를 순서대로 한 장씩 사용합니다.
  • 한 번 사용한 카드는 다시 사용할 수 없습니다.
  • 카드를 사용하지 않고 다음 카드로 넘어갈 수 없습니다.
  • 기존에 주어진 카드 뭉치의 단어 순서는 바꿀 수 없습니다.

문제 조건에 유의하여 아래와 같은 방법으로 풀이했다.

  1. goal 배열(만들어야 하는 문장)을 기준으로 순회
  2. 순회 중 cards1 또는 cards2에 goal의 요소인 part와 일치하는게 있다면 문장이 잘 만들어지고 있으므로 계속 진행(진행할 때 이미 사용한 카드는 사용하지 못하므로 사용한 카드의 배열의 인덱스를 1씩 증가)
  3. 그렇지 않다면 문장이 잘못 만들어 진 것이므로 바로 "No"를 리턴

PackOfCards.java

package com.example.Programmers.Lv1;

/**
 * 프로그래머스 Lv1 - 카드 뭉치
 */
public class PackOfCards {
    public String solution(String[] cards1, String[] cards2, String[] goal) {
        String answer = "Yes";
        int idx1 = 0;
        int idx2 = 0;
        int length1 = cards1.length - 1;
        int length2 = cards2.length - 1;

        for (String part : goal) {
            if (idx1 <= length1 && cards1[idx1].equals(part)) {
                idx1++;
            } else if (idx2 <= length2 && cards2[idx2].equals(part)) {
                idx2++;
            } else {
                return "No";
            }
        }
        return answer;
    }
}

PackOfCardsTest.java

package com.example.Programmers.Lv1;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class PackOfCardsTest {
    @Test
    public void testPackOfCards() {
        PackOfCards p = new PackOfCards();

        String result1 = p.solution(new String[] { "i", "drink", "water" }, new String[] { "want", "to" },
                new String[] { "i", "want", "to", "drink", "water" });
        String result2 = p.solution(new String[] { "i", "water", "drink" }, new String[] { "want", "to" },
                new String[] { "i", "want", "to", "drink", "water" });

        assertEquals("Yes", result1);
        assertEquals("No", result2);
    }
}
profile
나의 개발로그

0개의 댓글