748 LeetCode 最短完整词

题目描述:
在这里插入图片描述
思路:
1、用map记录牌照当中的字母和出现的次数(并且把出现的大写字母转换成小写字母)
2、用map记录单词列表的每个单词的字母的出现次数,然后与牌照当中的记录相比较
3、存下第一个符合要求的单词,然后当再有符合要求的单词时,与上一个单词的长度进行比较,短与上一个单词时,替换上一个单词,反之继续

代码如下:

class Solution {
public:
    string shortestCompletingWord(string licensePlate, vector<string>& words) {
        map<char,int>letter;
        map<char,int>cur;
        vector<char>alph;
        string res;
        for(int i=0;i<licensePlate.size();i++){
            if(licensePlate[i]>='a'&&licensePlate[i]<='z'){
            letter[licensePlate[i]]++;
            alph.push_back(licensePlate[i]);}
            if(licensePlate[i]>='A'&&licensePlate[i]<='Z'){
                licensePlate[i]+=32;
                letter[licensePlate[i]]++;
                alph.push_back(licensePlate[i]);
            }
        }  
        int cnt=0;
        for(int i=0;i<words.size();i++){
            int flag=0;
            cur.clear();
            for(int j=0;j<words[i].size();j++){
                cur[words[i][j]]++;
            }
            for(int k=0;k<alph.size();k++){
                if(cur[alph[k]]<letter[alph[k]])
                flag=1;
            }
            if(flag==0){
               cnt++;
               if(cnt==1)
               {res=words[i];}
               if(words[i].size()<res.size())
                {res=words[i];}
            }
        }
        return res;
    }
};
发布了123 篇原创文章 · 获赞 0 · 访问量 954

猜你喜欢

转载自blog.csdn.net/peachzy/article/details/104347223
今日推荐