본문 바로가기
Algorithm Practice/Programmers

[Programmers] 카드뭉치 (Java / Python)

by 1000zoo 2023. 9. 1.

문제 링크

문제 설명

문자열 배열 cards1과 cards2 (카드뭉치)가 주어졌을 때, 두 문자열을 주어진 순서대로 사용하여 문자열 배열 goal를 만들 수 있다면 "Yes", 없다면 "No"를 리턴해야한다. 한 번 사용한 카드는 재사용 불가능하고, 카드뭉치의 순서는 바꿀 수 없다.

 

제한 사항

  • 각 카드 뭉치의 길이는 최대 10
  • goal은 cards1과 cards2의 단어들로만 이루어져 있으며, 최소 2개의 카드 뭉치의 단어를 조합해서 만들 수 있음
  • goal의 길이는 최소 2개 이상이고, 최대로 만들 수 있는 길이는 cards1, cards2의 길이의 합
  • 각 단어의 길이는 최대 10
  • 단어는 알파벳 소문자로만 이루어짐

입출력 예

cards1 cards2 goal result
["i", "drink", "water"] ["want", "to"] ["i", "want", "to", "drink", "water"] "Yes"

문제 풀이

위 문제는 주어진 카드뭉치를 조합하여, goal과 같은 문자열 배열을 만들 수 있는지 판단하는 문제이다. goal을 중심으로 반복문을 설정하고, goal의 문자열과 cards1, 혹은 cards2의 첫번째 원소 문자열을 비교한다. cards1의 문자열과 goal의 문자열이 일치한다면, cards1의 첫번째 문자열을 제거한다. 즉 Queue를 이용하여 문제를 해결하면 된다.

 

코드

Java

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";
    }
}

 

Python

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"
블로그 이전