My n*k prime solution


  • 0

    class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {

        List<List<String>> result = new ArrayList<>();
        if (strs == null || strs.length==0)
            return result;
        
        Map<Long, List<String>> map = new HashMap<>();
        
        for (String str : strs) {
            long mult = calculatePrime(str);
            System.out.println(str+":"+mult);
            if (map.containsKey(mult)) {
                List<String> sList = map.get(mult);
                sList.add(str);
                map.put(mult,sList);
            } else {
                map.put(mult,new ArrayList<>(Arrays.asList(str)));
            }
            
        }
        return new ArrayList<>(map.values());
    }
        
    private long calculatePrime(String str) {
        int[] primes = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,67,71,73,79,83,89,97,101,103};
    
        long mult = 1;
        for (int i =0; i < str.length(); i++) {
            mult *= primes[str.charAt(i)-'a'];
        }
        return mult;
    
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.