본문 바로가기
Problem Solving/LeetCode

[LeetCode] 748. Shortest Completing Word - Java

by graycode 2026. 10. 10.

• 문제 링크

 

Shortest Completing Word - LeetCode

Can you solve this real interview question? Shortest Completing Word - Given a string licensePlate and an array of strings words, find the shortest completing word in words. A completing word is a word that contains all the letters in licensePlate. Ignore

leetcode.com

 

• 풀이 코드

public class Solution {

    public String shortestCompletingWord(String licensePlate, String[] words) {
        int[] tgt = getFrequency(licensePlate);
        String s = null;
        for (String word : words) if ((s == null || word.length() < s.length()) && isCompleting(tgt, word)) s = word;

        return s;
    }

    private int[] getFrequency(String s) {
        int[] freq = new int[26];
        for (char c : s.toLowerCase().toCharArray()) if (c >= 'a' && c <= 'z') freq[c - 'a']++;

        return freq;
    }

    private boolean isCompleting(int[] tgt, String word) {
        int[] freq = getFrequency(word);
        for (int i = 0; i < 26; i++) if (freq[i] < tgt[i]) return false;

        return true;
    }

}

댓글