Leetcode 748. Shortest Completing Word
You are given a string licensePlate
and an array of strings words
. The licensePlate
string consists of alphanumeric characters and spaces. The spaces and numbers in licensePlate
are irrelevant, and only the letters are relevant. Find the shortest completing word in words
. A completing word is one that contains all the letters in the licensePlate
(case insensitive). If there are multiple shortest completing words, return the first one that appears in the array.
licensePlate
and words
? Typically constraints will be provided, but for this problem, consider reasonable limits (e.g., up to 1000 words, each up to 1000 characters).licensePlate
? Ignore non-alphabetic characters.licensePlate
ignoring spaces and numbers. Convert all letters to lowercase.words
, create a count of its letters.import java.util.*;
public class Solution {
public String shortestCompletingWord(String licensePlate, String[] words) {
// Extract the character count from the license plate
int[] licenseCount = getCharCount(licensePlate.toLowerCase());
String shortest = null;
for (String word : words) {
if (matches(licenseCount, getCharCount(word.toLowerCase()))) {
if (shortest == null || word.length() < shortest.length()) {
shortest = word;
}
}
}
return shortest;
}
private int[] getCharCount(String str) {
int[] count = new int[26];
for (char c : str.toCharArray()) {
if (Character.isLetter(c)) {
count[c - 'a']++;
}
}
return count;
}
private boolean matches(int[] licenseCount, int[] wordCount) {
for (int i = 0; i < 26; i++) {
if (licenseCount[i] > wordCount[i]) {
return false;
}
}
return true;
}
}
n
is the length of the string.m
be the number of words and l
be the average length of the words. The overall complexity is O(m * l) since we process each word individually.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?