All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g2301_2400.s2306_naming_a_company.Solution Maven / Gradle / Ivy

There is a newer version: 1.24
Show newest version
package g2301_2400.s2306_naming_a_company;

// #Hard #Array #String #Hash_Table #Bit_Manipulation #Enumeration
// #2022_06_15_Time_486_ms_(74.14%)_Space_83.3_MB_(58.98%)

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Solution {
    private long count(Map> map, char a, char b) {
        if (!map.containsKey(a) || !map.containsKey(b)) {
            return 0;
        }
        long common = 0;
        Set first = map.get(a);
        Set second = map.get(b);
        for (String c : first) {
            if (second.contains(c)) {
                common++;
            }
        }
        long uniqueA = first.size() - common;
        long uniqueB = second.size() - common;
        return uniqueA * uniqueB * 2L;
    }

    public long distinctNames(String[] ideas) {
        long ans = 0;
        Map> map = new HashMap<>();
        for (String idea : ideas) {
            char startChar = idea.charAt(0);
            Set values = map.getOrDefault(startChar, new HashSet<>());
            values.add(idea.substring(1));
            map.put(startChar, values);
        }
        for (int i = 0; i <= 26; i++) {
            for (int j = i + 1; j <= 26; j++) {
                long unique = count(map, (char) (i + 'a'), (char) (j + 'a'));
                ans += unique;
            }
        }
        return ans;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy