这题没啥好说的,但是我理解题意理解了好久。。。

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:
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:
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.

就是统计一下字母出现的次数而已,大于等于就行了。

static std::string Main(std::string licensePlate,
                            const std::vector<std::string> &words) {
        int nLicenseCharCnt[26] = {0};
        for (auto v : licensePlate) {
            if ((v >= 'a' && v <= 'z') || (v >= 'A' && v <= 'Z')) {
                if (v >= 'A' && v <= 'Z') {
                    v = 'a' + v - 'A';
                }
                nLicenseCharCnt[v - 'a']++;
            }
        }

        std::string res;
        for (auto &word : words) {
            int nArray[26];
            memcpy(nArray, nLicenseCharCnt, sizeof(nLicenseCharCnt));
            for (auto v : word) {
                nArray[v - 'a']--;
            }
            bool bAllNegOrZero = true;
            for (auto v : nArray) {
                if (v > 0) {
                    bAllNegOrZero = false;
                }
            }
            if (!bAllNegOrZero) {
                continue;
            }
            if (res.empty() || word.length() < res.length()) {
                res = word;
            }
        }
        return res;
    }
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day