Group Anagrams

给一个字符串组, 把其中的anagrams成组. 这个题用hash来找, 因为知道anagram就是把一个字符串打散. 所以他们的hash都相同.

public class Solution {
    private int hash(int[] count) {
        int a = 3;
        int b = 7;
        int hash = 0;
        for(int n : count) {
            hash = hash*a + n;
            a = a * b;
        }
        return hash;
    }
    public ArrayList<String> anagrams(String[] strs) {
        if(strs.length == 0 || strs == null)
            return null;
        HashMap<Integer,ArrayList<String>> m = new HashMap<Integer, ArrayList<String>>();
        for(String s : strs) {
            int[] count = new int[26];
            for(int i = 0 ; i < s.length(); i++){
                count[s.charAt(i) - 'a'] ++;
            }
            int h = hash(count);
            if(!m.containsKey(h)){
                m.put(h, new ArrayList<String>());
            }
            m.get(h).add(s);
        }
        ArrayList<String> res = new ArrayList<String>();
        for(ArrayList<String> ary : m.values()){
            if(ary.size() > 1)
                res.addAll(ary);
        }
        return res;
    }
}