|
| 1 | +/** |
| 2 | + * 748. Shortest Completing Word |
| 3 | + * https://leetcode.com/problems/shortest-completing-word/ |
| 4 | + * Difficulty: Easy |
| 5 | + * |
| 6 | + * Given a string licensePlate and an array of strings words, find the shortest completing |
| 7 | + * word in words. |
| 8 | + * |
| 9 | + * A completing word is a word that contains all the letters in licensePlate. Ignore numbers |
| 10 | + * and spaces in licensePlate, and treat letters as case insensitive. If a letter appears more |
| 11 | + * than once in licensePlate, then it must appear in the word the same number of times or more. |
| 12 | + * |
| 13 | + * For example, if licensePlate = "aBc 12c", then it contains letters 'a', 'b' (ignoring case), |
| 14 | + * and 'c' twice. Possible completing words are "abccdef", "caaacab", and "cbca". |
| 15 | + * |
| 16 | + * Return the shortest completing word in words. It is guaranteed an answer exists. If there |
| 17 | + * are multiple shortest completing words, return the first one that occurs in words. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {string} licensePlate |
| 22 | + * @param {string[]} words |
| 23 | + * @return {string} |
| 24 | + */ |
| 25 | +var shortestCompletingWord = function(licensePlate, words) { |
| 26 | + const license = licensePlate.toLowerCase().replace(/[\d\s]+/g, ''); |
| 27 | + const sortedWords = [...words].sort((a, b) => a.length - b.length); |
| 28 | + |
| 29 | + for (const word of sortedWords) { |
| 30 | + let updatedLicense = license; |
| 31 | + |
| 32 | + for (let i = 0; i < word.length; i++) { |
| 33 | + updatedLicense = updatedLicense.replace(word[i], ''); |
| 34 | + if (!updatedLicense) { |
| 35 | + return word; |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | +}; |
0 commit comments