|
| 1 | +# Time: O(n) |
| 2 | +# Space: O(1) |
| 3 | + |
| 4 | +# Find the minimum length word from a given dictionary words, |
| 5 | +# which has all the letters from the string licensePlate. |
| 6 | +# Such a word is said to complete the given string licensePlate |
| 7 | +# |
| 8 | +# Here, for letters we ignore case. |
| 9 | +# For example, "P" on the licensePlate still matches "p" on the word. |
| 10 | +# |
| 11 | +# It is guaranteed an answer exists. |
| 12 | +# If there are multiple answers, return the one that occurs first in the array. |
| 13 | +# |
| 14 | +# The license plate might have the same letter occurring multiple times. |
| 15 | +# For example, given a licensePlate of "PP", |
| 16 | +# the word "pair" does not complete the licensePlate, but the word "supper" does. |
| 17 | +# |
| 18 | +# Example 1: |
| 19 | +# Input: licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"] |
| 20 | +# Output: "steps" |
| 21 | +# Explanation: The smallest length word that contains the letters "S", "P", "S", and "T". |
| 22 | +# Note that the answer is not "step", because the letter "s" must occur in the word twice. |
| 23 | +# Also note that we ignored case for the purposes of comparing whether a letter exists in the word. |
| 24 | +# Example 2: |
| 25 | +# Input: licensePlate = "1s3 456", words = ["looks", "pest", "stew", "show"] |
| 26 | +# Output: "pest" |
| 27 | +# Explanation: There are 3 smallest length words that contains the letters "s". |
| 28 | +# We return the one that occurred first. |
| 29 | +# Note: |
| 30 | +# - licensePlate will be a string with length in range [1, 7]. |
| 31 | +# - licensePlate will contain digits, spaces, or letters (uppercase or lowercase). |
| 32 | +# - words will have a length in the range [10, 1000]. |
| 33 | +# - Every words[i] will consist of lowercase letters, and have length in range [1, 15]. |
| 34 | + |
| 35 | +class Solution(object): |
| 36 | + def shortestCompletingWord(self, licensePlate, words): |
| 37 | + """ |
| 38 | + :type licensePlate: str |
| 39 | + :type words: List[str] |
| 40 | + :rtype: str |
| 41 | + """ |
| 42 | + def contains(counter1, w2): |
| 43 | + c2 = collections.Counter(w2.lower()) |
| 44 | + c2.subtract(counter1) |
| 45 | + return all(map(lambda x: x >= 0, c2.values())) |
| 46 | + |
| 47 | + result = None |
| 48 | + counter = collections.Counter(c.lower() for c in licensePlate if c.isalpha()) |
| 49 | + for word in words: |
| 50 | + if (result is None or (len(word) < len(result))) and \ |
| 51 | + contains(counter, word): |
| 52 | + result = word |
| 53 | + return result |
0 commit comments