---
# System prepended metadata

title: 2306. Naming a Company
tags: [Leetcode, String, Hard]

---

# 2306. Naming a Company
###### tags: `Leetcode` `Hard` `String`
Link: https://leetcode.com/problems/naming-a-company/description/
## 思路
思路参考[这里](https://leetcode.com/problems/naming-a-company/solutions/2141038/python-explanation-with-pictures-group/)
group by 首字母
对于两个不同的首字母 每一个首字母对应一个set set里面放着所有以它开头的字串的去掉首字母的substring
对于每两个首字母 先用一个set把两个set合并起来就知道有多少string是在这两个set里面都有了
剔除掉duplicate substring剩下的就是可以组成name的idea
## Code
```java=
class Solution {
    public long distinctNames(String[] ideas) {
        Set<String>[] sets = new HashSet[26];
        for(int i=0; i<26; i++) sets[i] = new HashSet<>();
        for(String idea:ideas){
            sets[idea.charAt(0)-'a'].add(idea.substring(1));
        }
        long ans = 0;
        for(int i=0; i<26; i++){
            if(sets[i].size()==0) continue;
            for(int j=i+1; j<26; j++){
                if(sets[j].size()==0) continue;
                Set<String> union = new HashSet<>();
                union.addAll(sets[i]);
                union.addAll(sets[j]);
                int duplicate = sets[i].size()+sets[j].size()-union.size();
                ans += (sets[i].size()-duplicate)*(sets[j].size()-duplicate)*2;
            }
        }
        return ans;
    }
}
```