leetcode 748. 最短完整词

题目

如果单词列表(words)中的一个单词包含牌照(licensePlate)中所有的字母,那么我们称之为完整词。在所有完整词中,最短的单词我们称之为最短完整词。
单词在匹配牌照中的字母时不区分大小写,比如牌照中的 “P” 依然可以匹配单词中的 “p” 字母。
我们保证一定存在一个最短完整词。当有多个单词都符合最短完整词的匹配条件时取单词列表中最靠前的一个。
牌照中可能包含多个相同的字符,比如说:对于牌照 “PP”,单词 “pair” 无法匹配,但是 “supper” 可以匹配。

题解一(个人)
思路: 把licensePlate转换成小写,先用一个数组统计licensePlate中的各个字母个数,然后统计word每一个单词中各个字母个数。当前者的某个字母个数小于等于后者某个单词的该字母个数并且这个单词长度更短时就更新,否则跳到下一个单词。
时间: 26ms
代码:

class Solution {
    public String shortestCompletingWord(String licensePlate, String[] words) {
        licensePlate=licensePlate.toLowerCase();
        int[] map=new int[127];
        String res="";
        for(int i=0;i<licensePlate.length();i++){
            if(licensePlate.charAt(i)>='a'&&licensePlate.charAt(i)<='z'){
               map[licensePlate.charAt(i)]++;
            }
        }
        outer:
        for(int i=0;i<words.length;i++){
            
            int[] temp=new int[127];
            for(int j=0;j<words[i].length();j++){
                temp[words[i].charAt(j)]++;
            }
            for(int j=0;j<map.length;j++){
                if(temp[j]<map[j])continue outer;
            }
            if(res.length()==0)res=words[i];
            else
            res=(res.length()<=words[i].length()?res:words[i]);
        }
        return res;
    }
}

题解二(leetcode优解)
思路相似,但是实现细节更优
时间: 7ms
代码:

class Solution {
    public String shortestCompletingWord(String licensePlate, String[] words) {
        int[] lp = new int[26];
        for (int i =0;i<licensePlate.length();i++)
        {
            char ch = licensePlate.charAt(i);
            if (ch>=65 && ch<=90)
            {
                ch = (char) (ch + 32);
            }
            if (ch>=97 && ch<=122)
            {
                lp[ch-97]++;
            }
        }
        int cnt = Integer.MAX_VALUE;
        String res = null;
        for (String word : words)
        {
            if (isComplete(word,lp))
            {
                if (cnt>word.length())
                {
                    cnt = word.length();
                    res = word;
                }
            }
        }
        return res;
    }

    static boolean isComplete(String word , int [] lp)
    {
        int [] wcnt = new int[26];
        char[] chars = word.toCharArray();
        for (char ch : chars)
        {
            wcnt[ch-97]++;
        }
        for (int i = 0;i<lp.length;i++)
        {
            if (lp[i]>wcnt[i])
            {
                return false;
            }
        }
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值