LeetCode 748. 最短完整词
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 748. 最短完整词
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 題目
如果單詞列表(words)中的一個單詞包含牌照(licensePlate)中所有的字母,那么我們稱之為完整詞。
在所有完整詞中,最短的單詞我們稱之為最短完整詞。
單詞在匹配牌照中的字母時不區分大小寫,比如牌照中的 “P” 依然可以匹配單詞中的 “p” 字母。
我們保證一定存在一個最短完整詞。
當有多個單詞都符合最短完整詞的匹配條件時取單詞列表中最靠前的一個。
牌照中可能包含多個相同的字符,比如說:對于牌照 “PP”,單詞 “pair” 無法匹配,但是 “supper” 可以匹配。
示例 1: 輸入:licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"] 輸出:"steps" 說明:最短完整詞應該包括 "s"、"p"、"s" 以及 "t"。 對于 "step" 它只包含一個 "s" 所以它不符合條件。 同時在匹配過程中我們忽略牌照中的大小寫。示例 2: 輸入:licensePlate = "1s3 456", words = ["looks", "pest", "stew", "show"] 輸出:"pest" 說明:存在 3 個包含字母 "s" 且有著最短長度的完整詞, 但我們返回最先出現的完整詞。注意: 牌照(licensePlate)的長度在區域[1, 7]中。 牌照(licensePlate)將會包含數字、空格、或者字母(大寫和小寫)。 單詞列表(words)長度在區間 [10, 1000] 中。 每一個單詞 words[i] 都是小寫,并且長度在區間 [1, 15] 中。來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/shortest-completing-word
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
class Solution { public:string shortestCompletingWord(string licensePlate, vector<string>& words) {unordered_map<char,int> m;for(char c : licensePlate)if(isalpha(c))m[tolower(c)]++;//字符計數unordered_map<char,int> wc;int minLen = INT_MAX;bool flag;string ans;for(string word : words){wc.clear();flag = true;for(char c : word)if(isalpha(c))wc[c]++;//單詞字符計數for(auto lpChar : m){if(wc.find(lpChar.first) == wc.end() || wc[lpChar.first] < lpChar.second){ //單詞中沒有這個牌照字符,或者不夠flag = false;break;}}if(flag){if(word.size() < minLen){minLen = word.size();ans = word;}}}return ans;} };48 ms 15 MB
總結
以上是生活随笔為你收集整理的LeetCode 748. 最短完整词的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 1418. 点菜展示表
- 下一篇: LeetCode MySQL 1083.