https://school.programmers.co.kr/learn/courses/30/lessons/159994
문자열 배열 cards1과 cards2 (카드뭉치)가 주어졌을 때, 두 문자열을 주어진 순서대로 사용하여 문자열 배열 goal를 만들 수 있다면 "Yes", 없다면 "No"를 리턴해야한다. 한 번 사용한 카드는 재사용 불가능하고, 카드뭉치의 순서는 바꿀 수 없다.
cards1 | cards2 | goal | result |
---|---|---|---|
["i", "drink", "water"] | ["want", "to"] | ["i", "want", "to", "drink", "water"] | "Yes" |
["i", "water", "drink"] | ["want", "to"] | ["i", "want", "to", "drink", "water"] | "No" |
위 문제는 주어진 카드뭉치를 조합하여, goal과 같은 문자열 배열을 만들 수 있는지 판단하는 문제이다. goal을 중심으로 반복문을 설정하고, goal의 문자열과 cards1, 혹은 cards2의 첫번째 원소 문자열을 비교한다. cards1의 문자열과 goal의 문자열이 일치한다면, cards1의 첫번째 문자열을 제거한다. 즉 Queue를 이용하여 문제를 해결하면 된다.
public class WordCardDeck {
public String solution(String[] cards1, String[] cards2, String[] goal) {
int index1 = 0, index2 = 0;
for (String word : goal) {
String word1 = index1 < cards1.length ? cards1[index1] : "";
String word2 = index2 < cards2.length ? cards2[index2] : "";
if (word1.equals(word)) {
index1++;
} else if (word2.equals(word)) {
index2++;
} else {
return "No";
}
}
return "Yes";
}
}
def solution(cards1, cards2, goal):
while goal:
if cards1 and goal[0] == cards1[0]:
cards1.pop(0)
goal.pop(0)
continue
else:
if cards2 and goal[0] == cards2[0]:
cards2.pop(0)
goal.pop(0)
continue
else:
return "No"
return "Yes"