Group Anagrams

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return:

[ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ]

Note: All inputs will be in lower-case.

Solution

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

         Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();

        for (String s : strs) {
            int hashValue = hash(s);
            List<String> temp = new ArrayList<String>();
            temp.add(s);

            map.merge(hashValue, temp, (a, b) -> {
                a.addAll(b);
                return a;
            });
        }

        for (List<String> lst: map.values()) {
            Collections.sort(lst);
        }

        return map.values().stream().collect(Collectors.toList());
    }

    private int hash(String s) {
        int hash = 0;
        int a = 378551;
        int b = 63689;

        int[] count = new int[26];
        for(char ch: s.toCharArray()) {
            count[ch-'a'] ++;
        }
        for (int ch : count) {
            hash = hash * a + ch;
            a = a * b;
        }
        return hash;
    }
}

results matching ""

    No results matching ""