力扣每日一题 2306.公司命名

做题过程中使用到的java语法:

1.从一个字符串中取出一部分字符串:

String str = "Hello, World!";  
String part = str.substring(7); // 从索引7开始到字符串末尾  
System.out.println(part); // 输出: World!

class Solution {

    public long distinctNames(String[] ideas) {

        Map<Character, Set<String>> names = new HashMap<Character, Set<String>>();

        //首先建立了一个双列集合

        for (String idea : ideas) {

            names.putIfAbsent(idea.charAt(0), new HashSet<String>());

            //putIfAbsent是map接口中的一个方法,如果指定的键尚未与某个值相关联

            //则将其与给定的值相关联

            //段代码的目的是确保names这个Map中,以idea字符串的第一个字符为键的映射存在

            //且其值是一个新的HashSet<String>实例(如果之前不存在这样的映射)。

            names.get(idea.charAt(0)).add(idea.substring(1));

        }

        long ans = 0;

        for (Map.Entry<Character, Set<String>> entryA : names.entrySet()) {

            char preA = entryA.getKey();

            Set<String> setA = entryA.getValue();

            for (Map.Entry<Character, Set<String>> entryB : names.entrySet()) {

                char preB = entryB.getKey();

                Set<String> setB = entryB.getValue();

                if (preA == preB) {

                    continue;

                }

                int intersect = getIntersectSize(setA, setB);

                //getIntersectSize方法的目的是计算并返回这两个集合的交集的大小

                //即这两个集合中共有的元素的数量。

                ans += (long) (setA.size() - intersect) * (setB.size() - intersect);

            }

        }

        return ans;

    }

    public int getIntersectSize(Set<String> a, Set<String> b) {

        int ans = 0;

        for (String s : a) {

            if (b.contains(s)) {

                ans++;

            }

        }

        return ans;

    }

}


 

//想想可以边做循环边判断吗?

//如果两个候选名字拥有同样的首字母

//那么他们一定无法得到有效的公司名字

//如果两个候选名字拥有不同的首字母,那么他们可能得到有效的公司名字

//假设现在一共有如下几个单词:

//Aa Ab Ac Ba Bb Bc

//names[preA]=Aa Ab Ac Ad Af

//names[preB]=Ba Bb Bc Bx Br

//

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值