748. 最短补全词( Shortest Completing Word) 3ms做法心得

在这里插入图片描述
在这里插入图片描述
做法大致就是将每个字符对应的ASCII码-'a'后存进数组,然后对照两个数组来求最优解。
在这里插入图片描述

import java.util.Locale;

//748. 最短补全词
public class ShortestCompletingWord {
    public static void main(String[] args) {
        String str="da A  a54";

        System.out.println(new ShortestCompletingWord().shortestCompletingWord("OgEu755",new String[]{"enough","these","play","wide","wonder","box","arrive","money","tax","thus"}));


    }


    public String shortestCompletingWord(String licensePlate, String[] words) {
     String str="";
    int bestsum=0;
    int []arr=new int[26];

    //将字符串变为小写,再将里面的数字和空格排除,然后将剩下的字符存入数组里
        licensePlate=licensePlate.toLowerCase(Locale.ROOT);
        for (int i = 0; i < licensePlate.length(); i++) {
            if (licensePlate.charAt(i)>=97&&licensePlate.charAt(i)<=122){
              arr[licensePlate.charAt(i)-'a']++;
            }
    }
        //逐个遍历字符数组里的字符
        for (int i = 0; i < words.length; i++) {
            //创建/清空临时数组
            int []arrnew=new int[26];
            //将他的字符存入arrnew数组里
            for (int i1 = 0; i1 < words[i].length(); i1++) {
              arrnew[words[i].charAt(i1)-'a']++;
            }
            //设置开关,用来判断是否该字符串包含我们的licensePlate字符串里的字符
            int bool=1;
            //判断是否该字符串包含licensePlate字符串里的字符
            for (int i1 = 0; i1 < arr.length; i1++)
                //如果不包含将开关关闭,退出循环
                if (arr[i1]>0) if (arrnew[i1]<arr[i1]) {
                    bool=0;
                    break;
                }
           //如果开关开着,判断和最有解比较,判断是否为最优解
            if (bool==1) {
                if(bestsum==0){
                    bestsum=words[i].length();
                    str=words[i];

                }else {
                    if (words[i].length()<bestsum) {
                        bestsum=words[i].length();
                        str=words[i];
                    }
                }

            }

        }
        return str;
}
}

了解更多可以看将字符存入数组

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值