Problem
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 numbers and spaces in licensePlate, and treat letters as case insensitive. If a letter appears more than once in licensePlate, then it must appear in the word the same number of times or more.
For example, if licensePlate = “aBc 12c”, then it contains letters ‘a’, ‘b’ (ignoring case), and ‘c’ twice. Possible completing words are “abccdef”, “caaacab”, and “cbca”.
Return the shortest completing word in words. It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words.
Algorithm
Count the list and the number of occurrences of each letter in each word and compare them.
Code
class Solution:
def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:
dict_cnts = [0] * 26
for c in licensePlate:
if c >= 'a' and c <= 'z':
index = ord(c) - ord('a')
dict_cnts[index] = dict_cnts[index] + 1
elif c >= 'A' and c <= 'Z':
index = ord(c) - ord('A')
dict_cnts[index] = dict_cnts[index] + 1
min_len = 20
min_id = -1
slen = len(words)
for i in range(slen):
word_cnts = [0] * 26
wlen = len(words[i])
for c in words[i]:
if c >= 'a' and c <= 'z':
index = ord(c) - ord('a')
word_cnts[index] = word_cnts[index] + 1
elif c >= 'A' and c <= 'Z':
index = ord(c) - ord('A')
word_cnts[index] = word_cnts[index] + 1
find = 1
for j in range(26):
if dict_cnts[j] > word_cnts[j]:
find = 0
break
if find and min_len > wlen:
min_len = wlen
min_id = i
if min_id >= 0:
return words[min_id]
else:
return ""