프로그래머스 문제 중 레벨 1 카드 뭉치 문제를 풀이했다.
연습문제로 분류되어있어서 그런지 난이도는 어렵지 않았다.
문제 조건
- 원하는 카드 뭉치에서 카드를 순서대로 한 장씩 사용합니다.
- 한 번 사용한 카드는 다시 사용할 수 없습니다.
- 카드를 사용하지 않고 다음 카드로 넘어갈 수 없습니다.
- 기존에 주어진 카드 뭉치의 단어 순서는 바꿀 수 없습니다.
문제 조건에 유의하여 아래와 같은 방법으로 풀이했다.
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);
}
}