748. Shortest Completing Word

问题描述:给你一个字符串licensePlate,字符串中包含大小写字母,空格,数字。判断字符串数组words中,哪个字符串包含了licensePlate中所有的字母(大小写不敏感).
思路:将licensePlate预处理,全部转换为小写,去除数字,空格。然后对出现的字母进行统计。随后遍历words中每个字符串。根据之前的记录判断字符串是否包含所有的字母。
原答案:

    public String shortestCompletingWord(String licensePlate, String[] words) {
        licensePlate=licensePlate.toLowerCase();
        int length=licensePlate.length();
        char[] charArray=new char[length];
        int position=0;
        Map<Character,Integer> map=new HashMap<Character,Integer>();
        for(int i=0;i<length;i++){
            char chr=licensePlate.charAt(i);
               if((chr>='A'&&chr<='Z')||(chr>='a'&&chr<='z')){
                   if(map.containsKey(chr)){
                       map.put(chr,map.get(chr)+1);
                   }else{
                       charArray[position]=chr;
                       map.put(chr,1);
                       position++;
                   }
               }
        }
        licensePlate=new String(charArray);
        licensePlate=licensePlate.trim();
        int checkLenth=licensePlate.length();
        int wordsLength=words.length;
        String[] result=new String[wordsLength];
        int resPos=0;
        for(int j=0;j<wordsLength;j++){
            int count=0;
            Map<Character,Integer> temp=new HashMap<Character,Integer>(map);
            String word=words[j];
            length=word.length();
            for(int k=0;k<length;k++){
                char c=word.charAt(k);
                if(temp.containsKey(c)&&temp.get(c)>0){
                    temp.put(c, temp.get(c)-1);
                }
            }
            for(int k=0;k<checkLenth;k++){
                count=count+(temp.get(licensePlate.charAt(k)));
            }
            if(count==0){
                result[resPos]=word;
                resPos++;
            }
        }
        int minLength=1000;
        resPos=0;
        for(int j=0;j<wordsLength;j++){
            String word=result[j];
            if(word!=null){
            int workLength=word.length();
            if(workLength>0&&workLength<minLength){
                minLength=word.length();
                resPos=j;
            }
            }
        }
        return result[resPos];
    }

仓促下写成,最佳答案待补完

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值