Find the minimum length word from a given dictionarywords, which has all the letters from the stringlicensePlate. Such a word is said tocompletethe given stringlicensePlate

Here, for letters we ignore case. For example,"P"on thelicensePlatestill matches"p"on the word.

It is guaranteed an answer exists. If there are multiple answers, return the one that occurs first in the array.

The license plate might have the same letter occurring multiple times. For example, given alicensePlateof"PP", the word"pair"does not complete thelicensePlate, but the word"supper"does.

class Solution {
    public String shortestCompletingWord(String licensePlate, String[] words) {
        licensePlate = licensePlate.toLowerCase();
        int[] count = new int[26];
        for(int i = 0; i < licensePlate.length(); i++) {
            char c = licensePlate.charAt(i);
            if(c >= 'a' && c <= 'z') {
                count[c - 'a']++;
            }
        }

        String res = "";
        int len = Integer.MAX_VALUE;

        for(String word: words) {
            int[] curr = new int[26];
            for(int i = 0; i < word.length(); i++) {
                char c = word.charAt(i);
                if(c >= 'a' && c <= 'z') {
                    curr[c - 'a']++;
                }
            }

            if(contain(curr, count)) {
                if(word.length() < len) {
                    res = word;
                    len = word.length();
                }
            }
        }

        return res;
    }

    public boolean contain(int[] count1, int[] count2) {
        for(int i = 0; i < count2.length; i++) {
            if(count1[i] < count2[i])
                return false;
        }

        return true;
    }
}

results matching ""

    No results matching ""