Leetcode 748. 最短完整词 C++

Leetcode 748. 最短完整词

题目

如果单词列表(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" 且有着最短长度的完整词,但我们返回最先出现的完整词。

注意:

  1. 牌照(licensePlate)的长度在区域[1, 7]中。
  2. 牌照(licensePlate)将会包含数字、空格、或者字母(大写和小写)。
  3. 单词列表(words)长度在区间 [10, 1000]中。
  4. 每一个单词 words[i] 都是小写,并且长度在区间 [1, 15] 中。

题解

模拟
我们不妨把牌照中的字母统一为小写,我们计算每个字母出现的次数。
根据要求,当有多个单词都符合最短完整词的匹配条件时取单词列表中最靠前的一个。我们不妨对单词表根据长度进行稳定排序,即使用stable_sort函数。然后暴力判断当前单词是否可以匹配拍照。
详细过程见代码

代码

bool sortS(string s1,string s2){		//用于排序
    return s1.length() < s2.length();
}
class Solution {
public:
    bool isBig(char c){		//判断是否为大写字母
        return c>='A'&&c<='Z';
    }
    bool isSmall(char c){		//判断是否为小写字母
        return c>='a'&&c<='z';
    }
    string shortestCompletingWord(string licensePlate, vector<string>& words) {
        unordered_map<char,int> time;
        int cnt = 0;
        for(int i=0; i<licensePlate.length(); i++){
            if(isBig(licensePlate[i])){		//大写字母统一为小写字母
                time[licensePlate[i]+'a'-'A']++;
                cnt++;
            }else if(isSmall(licensePlate[i])){
                time[licensePlate[i]]++;
                cnt++;
            }
        }
        stable_sort(words.begin(),words.end(),sortS);
        for(int i=0; i<words.size(); i++){
            unordered_map<char,int> time_ = time;
            int cnt_ = cnt;
            for(int j=0; j<words[i].length(); j++){
                if(time_[words[i][j]] == 0)    continue;
                time_[words[i][j]]--;
                cnt_--;
                if(cnt_ == 0)    return words[i]; 
            }
        }
        return "";
    }
};

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-completing-word
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值