프로그래머스 외계어 사전

KIMYEONGJUN·2026년 9월 26일
post-thumbnail

문제

내가 생각했을때 문제에서 원하는부분

PROGRAMMERS-962 행성에 불시착한 우주비행사 머쓱이는 외계행성의 언어를 공부하려고 합니다.
알파벳이 담긴 배열 spell과 외계어 사전 dic이 매개변수로 주어집니다.
spell에 담긴 알파벳을 한번씩만 모두 사용한 단어가 dic에 존재한다면 1, 존재하지 않는다면 2를 return하도록 solution 함수를 완성해주세요.

내가 이 문제를 보고 생각해본 부분

Arrays.sort(spell);와 String sortedSpell = String.join("", spell); 부분은 spell 배열에 있는 알파벳들을 알파벳순으로 정렬한 뒤 하나의 문자열로 합친다.
이것이 비교를 위한 기준 정답 문자열이 된다.
for (String word : dic) 반복문은 dic 배열에 있는 단어들을 하나씩 순서대로 꺼내서 검사한다.
char[] chars = word.toCharArray();와 Arrays.sort(chars);, String sortedWord = new String(chars); 부분은 꺼낸 단어를 글자 단위의 배열로 쪼갠 후 알파벳순으로 정렬한다.
그리고 다시 문자열 sortedWord로 변환한다. 이렇게 하면 순서가 섞여 있어도 알파벳 구성이 같다면 똑같은 문자열이 된다.
if (sortedSpell.equals(sortedWord)) 조건문은 기준이 되는 sortedSpell과 정렬된 단어 sortedWord가 완전히 똑같은지 비교한다.
똑같다면 spell의 모든 알파벳을 한 번씩 다 사용해 만든 단어라는 뜻이므로 즉시 1을 리턴한다.
반복문을 끝까지 다 돌았는데도 일치하는 단어를 하나도 찾지 못했다면 조건에 맞는 단어가 없다는 뜻이므로 2를 리턴한다.

코드로 구현

import java.util.Arrays;

class Solution {
    public int solution(String[] spell, String[] dic) {
        Arrays.sort(spell);
        String sortedSpell = String.join("", spell);
        
        for (String word : dic) {
            char[] chars = word.toCharArray();
            Arrays.sort(chars);
            String sortedWord = new String(chars);
            
            if (sortedSpell.equals(sortedWord)) {
                return 1;
            }
        }
        
        return 2;
    }
}

프로그래머스 코드

package programmers.programmers2;

import java.util.Arrays;

// 프로그래머스 외계어 사전
public class Main155 {
    static class Solution {
        public int solution(String[] spell, String[] dic) {
            Arrays.sort(spell);
            String sortedSpell = String.join("", spell);

            for (String word : dic) {
                char[] chars = word.toCharArray();
                Arrays.sort(chars);
                String sortedWord = new String(chars);

                if (sortedSpell.equals(sortedWord)) {
                    return 1;
                }
            }

            return 2;
        }
    }

    public static void main(String[] args) {
        Solution sol = new Solution();

        // 입출력 예 1
        String[] spell1 = {"p", "o", "s"};
        String[] dic1 = {"sod", "eocd", "qixm", "adio", "soo"};
        System.out.println(sol.solution(spell1, dic1)); // 기대값: 2

        // 입출력 예 2
        String[] spell2 = {"z", "d", "x"};
        String[] dic2 = {"def", "dww", "dzx", "loveaw"};
        System.out.println(sol.solution(spell2, dic2)); // 기대값: 1

        // 입출력 예 3
        String[] spell3 = {"s", "o", "m", "d"};
        String[] dic3 = {"moos", "dzx", "smm", "sunmmo", "som"};
        System.out.println(sol.solution(spell3, dic3)); // 기대값: 2
    }
}

위에 있는 코드를 변경한 코드

마무리

코드와 설명이 부족할수 있습니다. 코드를 보시고 문제가 있거나 코드 개선이 필요한 부분이 있다면 댓글로 말해주시면 감사한 마음으로 참고해 코드를 수정 하겠습니다.

profile
Junior backend developer

0개의 댓글