외계어 사전

han.user();·2023년 4월 6일
0

프로그래머스

목록 보기
45/87
post-thumbnail

import java.util.*;

class Solution {
    public int solution(String[] spell, String[] dic) {
        // Set으로 dic 배열을 생성하여 중복된 값을 제거함
        Set<String> wordSet = new HashSet<>(Arrays.asList(dic));
        Arrays.sort(spell); // spell 배열을 사전순으로 정렬함

        List<String> wordList = new ArrayList<>(); // 조합을 저장할 리스트 생성
        generateCombinations("", spell, wordList); // spell 배열의 모든 조합을 생성하여 리스트에 추가함

        for (String word : wordList) {
            if (wordSet.contains(word)) { // 생성한 조합이 wordSet에 있는지 확인하여 있으면 1을 리턴함
                return 1;
            }
        }

        return 2; // 생성한 조합이 wordSet에 없으면 2를 리턴함
    }

    // spell 배열의 모든 조합을 생성하는 메소드
    private void generateCombinations(String current, String[] spell, List<String> combinations) {
        if (current.length() == spell.length) { // 현재 문자열의 길이가 spell 배열의 길이와 같으면 리스트에 추가하고 리턴함
            combinations.add(current);
            return;
        }

        for (int i = 0; i < spell.length; i++) {
            if (i > 0 && spell[i].equals(spell[i - 1])) { // 현재 알파벳이 이전 알파벳과 같으면 건너뛰기
                continue;
            }
            if (!current.contains(spell[i])) { // 현재 문자열에 현재 알파벳이 없으면 추가하고 재귀호출함
                generateCombinations(current + spell[i], spell, combinations);
            }
        }
    }
}
  • wordSet 변수는 dic 배열에서 중복된 값을 제거하여 Set으로 생성합니다.
  • spell 배열을 Arrays.sort() 메소드를 이용하여 사전순으로 정렬합니다.
  • wordList 변수는 조합을 저장할 ArrayList입니다. generateCombinations() 메소드를 이용하여
    spell 배열의 모든 조합을 생성하여 wordList에 추가합니다.
  • for 문을 이용하여 wordList에 저장된 각 조합이 wordSet에 있는지 검사합니다.
    조합이 wordSet에 있다면 1을 리턴하고, 없다면 2를 리턴합니다.
  • generateCombinations() 메소드는 재귀함수를 이용하여 spell 배열의 모든 조합을 생성합니다.
    current 변수에 현재까지 생성된 문자열을 저장하고, spell 배열에서 중복된 알파벳을 건너뛰며 재귀호출합니다.
profile
I'm still hungry.

0개의 댓글