题目大意: 给你一个由字母和数字组成车牌。另外给你一些单词,让你找一个最短的单词能够覆盖住车牌中的字母(不考虑大小写)。如果有多个解,输出第一个解。
Problem:
Find the minimum length word from a given dictionary words
, which has all the letters from the string licensePlate
. Such a word is said to complete the given string licensePlate
Here, for letters we ignore case. For example, "P"
on the licensePlate
still 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 a licensePlate
of "PP"
, the word "pair"
does not complete the licensePlate
, but the word "supper"
does.
Example 1:
1 2 3 4 5 |
Input: licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"] Output: "steps" Explanation: The smallest length word that contains the letters "S", "P", "S", and "T". Note that the answer is not "step", because the letter "s" must occur in the word twice. Also note that we ignored case for the purposes of comparing whether a letter exists in the word. |
Example 2:
1 2 3 4 |
Input: licensePlate = "1s3 456", words = ["looks", "pest", "stew", "show"] Output: "pest" Explanation: There are 3 smallest length words that contains the letters "s". We return the one that occurred first. |
Note:
licensePlate
will be a string with length in range[1, 7]
.licensePlate
will contain digits, spaces, or letters (uppercase or lowercase).words
will have a length in the range[10, 1000]
.- Every
words[i]
will consist of lowercase letters, and have length in range[1, 15]
.
Idea:
Hashtable
Solution:
C++
Time complexity: 时间复杂度 O(N*26), N is number of words.
Space complexity: 空间复杂度 O(26) = O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// Author: Huahua // Runtime: 15 ms class Solution { public: string shortestCompletingWord(string licensePlate, vector<string>& words) { vector<int> l(26, 0); for (const char ch : licensePlate) if (isalpha(ch)) ++l[tolower(ch) - 'a']; string ans; int min_l = INT_MAX; for (const string& word : words) { if (word.length() >= min_l) continue; if (!matches(l, word)) continue; min_l = word.length(); ans = word; } return ans; } private: bool matches(const vector<int>& l, const string& word) { vector<int> c(26, 0); for (const char ch : word) ++c[tolower(ch) - 'a']; for (int i = 0; i < 26; ++i) if (c[i] < l[i]) return false; return true; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment