Leetcode 748.最短补全词 与 tolower()函数 与 isalpha()函数

题目描述

题目地址
在这里插入图片描述

思路

首先阅读题干,了解题目的大意。

要从words中找出一个单词,满足:

  1. licensePlate中的所有字母都出现在该单词中,且每个单词的出现次数均大于等于licensePlate中的次数。
  2. 如果有多个单词满足要求,则优先返回长度最短的单词。
  3. 如果存在多个最短单词,则优先返回最先出现的单词。

注意:
1.licensePlate中不仅仅存在字母,还包括数字和空格,且字母也有大小写区分。
所以我们要用isalpha()函数来判定是否为字母,用tolower()来将字母全部转化成小写字母。

解题步骤

1.首先遍历licensePlate,将其中的字母存到map_license中。
2.从左到右依次遍历words数组,对每个word,有map_license中的每个字母的数量小于等于word中每个字母的数量。
3.如果满足上述条件,则再比较word的长度,存长度最短的单词进入string中。

代码实现

class Solution {
    
    
public:
    string shortestCompletingWord(string licensePlate, vector<string>& words) 
    {
    
    
        unordered_map<char,int> map_license;
        for(int i=0;i<licensePlate.size();i++)
        {
    
    
            if(isalpha(licensePlate[i]))  //isalpha() 如果是字母则返回非零
            {
    
    
                map_license[tolower(licensePlate[i])]++; //tolower()函数可以把小写字母转化成大写字母
            }
        }
        //若26个字母在words中的出现此处均不小于licensePlate,则满足,且返回最短单词。
        string res="aaaaaaaaaaaaaaaa";//因为word的最长长度为15,所以res初始化长度为16
        for(auto word : words)
        {
    
    
            unordered_map<char,int> map_word;
            bool flag=true;
            for(auto ch : word)
            {
    
    
                if(isalpha(ch))
                {
    
    
                    map_word[tolower(ch)]++;
                }
            }
            for(auto ch : map_license)
            {
    
    
                if(map_license[ch.first]>map_word[ch.first])
                {
    
    
                    flag=false;
                    break;
                }
                else
                {
    
    
                    continue;
                }
            }
            if(flag&&word.size()<res.size())
            {
    
    
                res=word;
            }

        }
        return res;

    }
};

总结

代码写的又臭又长,看看题解里的大佬,都很短

猜你喜欢

转载自blog.csdn.net/weixin_45847364/article/details/121855715
今日推荐