본문 바로가기
알고리즘 문제/Java

[LeetCode/Java] Shortest Completing Word

by 현장 2026. 7. 9.

-Code

public class LeetCode748 {
    // Shortest Completing Word
    public String shortestCompletingWord(String licensePlate, String[] words) {
        // 소문자 변환 및 알파벳이 아닌값 제거
        String convLicensePlate = licensePlate.toLowerCase()
                .replaceAll("[^a-z]", "");

        int[] alpaCnt = alpaCntCalc(convLicensePlate);
        int minLen = Integer.MAX_VALUE;
        String res = "";
        for (String word : words) {
            int[] nowWordCnt = alpaCntCalc(word);

            boolean flag = true;
            for (int i = 0; i < 26; i++) {
                if (nowWordCnt[i] < alpaCnt[i]) {
                    flag = false;
                    break;
                }
            }
            // 조건에 맞고 현재 최소 길이보다 작은 경우
            if (flag && minLen > word.length()) {
                res = word;
                minLen = word.length();
            };
        }
        return res;
    }
    // 알파벳 갯수 배열에 저장
    private static int[] alpaCntCalc(String str) {
        int[] alpaCnt = new int[26];
        for (char c : str.toCharArray()) {
            alpaCnt[c - 'a']++;
        }
        return alpaCnt;
    }
}

처음에 Map으로 할까 하다 너무 복잡하게 하는 것같이 int 배열로 바꾸고 길이에 따른 계산을 빼먹어서 해당 부분을 추가해 해결했습니다.

'알고리즘 문제 > Java' 카테고리의 다른 글

[LeetCode/Java] Unique Morse Code Words  (0) 2026.07.11
[LeetCode/Java] Flood Fill  (0) 2026.07.10
[LeetCode/Java] Reverse String II  (0) 2026.07.08
[LeetCode/Java] To Lower Case  (0) 2026.07.07
[LeetCode/Java] Binary Search  (0) 2026.07.06