求成功匹配的字符串总长度

import java.util.HashMap;


/**
 * @auther 飞行员夹克儿
 * @create 2021-11-01-21:30
 *
 *
 *给定一字符集合 a 和 一字符串集合 b;用集合 a 里的字符
 * 匹配集合 b 中的字符串,求成功匹配的字符串总长度;
 *
 *其中 a 匹配 b 中一个字符串时,a 中字符不能重复使用;
 * 但在匹配下一个字符串时,可重复使用;
 *
 * 输入
 * 字符集合a : {‘1’,‘2’,‘3’,‘4’,‘4’}
 * 字符串集合b:{‘123’,‘344’,‘112’,‘345’}
 * 输出
 * 集合b中字符串中,能与a匹配的有 123 与 344;顾输出总长度 6
 * 其中
 * 112不匹配是因为集合a中只有1个’1’
 * 345不匹配是因为集合a中没有
 *
 *
 */
public class Main1 {
    public static void main(String[] args) {
        char[] s1 = {'w','o','r','k','s'};
        String[] strings = {"work","wkor","works","woks"};

        HashMap<Character,Integer> map1 = new HashMap();
        for (char s: s1) {
            if (map1.get(s)==null){
                map1.put(s,1);
            }else{
                map1.put(s,(Integer)map1.get(s)+1);
            }

        }
        //System.out.println(map1);
        int count = 0;
        boolean b = true;
        for (String s:strings) {
            HashMap<Character,Integer> map2 = new HashMap();
            char[] chars = s.toCharArray();
            for (char c: chars) {
                if (map2.get(c)==null){
                    map2.put(c,1);
                }else{
                    map2.put(c,(Integer)map2.get(c)+1);
                }
            }
            //System.out.println(map2);

            for (char c:map2.keySet()) {
                if ((map1.get(c)== null ? 0 : map1.get(c)) < map2.get(c)){
                    b = false;
                }
            }
            if (b){
                count  += s.length();

            }

            b = true;

        }
        System.out.println(count);

    }
}


//使用getOrDefault优化
public class Main1 {
    public static void main(String[] args) {
        char[] s1 = {'w','o','r','k','s'};
        String[] strings = {"work","wkor","works","woks"};

        HashMap<Character,Integer> map1 = new HashMap();
        for (char s: s1) {
            map1.put(s,map1.getOrDefault(s,0)+1);
        }
        //System.out.println(map1);
        // 
        int count = 0;
        boolean b = true;
        for (String s:strings) {
            HashMap<Character,Integer> map2 = new HashMap();
            char[] chars = s.toCharArray();
            for (char c: chars) {
               map2.put(c,map2.getOrDefault(c, 0)+1);
            }
            //System.out.println(map2);

            for (char c:map2.keySet()) {
                if (map1.getOrDefault(c,0) < map2.get(c)){
                    b = false;
                }
            }
            if (b){
                count  += s.length();
            }
            b = true;
        }
        System.out.println(count);

    }
}

Map 的 getOrDefault( )
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值