49. Group Anagrams

来源:互联网 发布:windows sdk v8.1下载 编辑:程序博客网 时间:2024/05/01 23:42

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:
For the return value, each inner list’s elements must follow the lexicographic order.
All inputs will be in lower-case.

思路:把每个字符串进行重排序生成新的字符串,生成相同字符串的放在一起。

  public List<List<String>> groupAnagrams(String[] strs) {         List<List<String>> r = new ArrayList<List<String>>();         if (strs.length < 1) {            return r;        }        Arrays.sort(strs);        HashMap<String, List<String>> table = new HashMap<String, List<String>>();        for (String s : strs) {            char[] c = s.toCharArray();            Arrays.sort(c);            String t = new String(c);            if (table.containsKey(t)) {                List<String> tmp = table.get(t);                tmp.add(s);            }            else {                List<String> tmp = new ArrayList<String>();                tmp.add(s);                table.put(t, tmp);            }        }        Set<String> set = table.keySet();        for (String s :set) {            List<String> tmp = table.get(s);            r.add(tmp);        }        return r;    }

不排序的话可以考虑写一个hash函数:每个小写字母代表一个素数,hash函数就是字符串内所有字符代表质数的积,求得相同hash的放在一起。

 public List<List<String>> groupAnagrams(String[] strs) {         List<List<String>> r = new ArrayList<List<String>>();         if (strs.length < 1) return r;         //素数表        int[] prime = new int[]{2, 3, 5, 7, 11 ,13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 107};        Arrays.sort(strs);        HashMap<Integer, List<String>> table = new HashMap<Integer, List<String>>();        for (String s : strs) {            char[] c = s.toCharArray();            //计算hash            int primes = 1;            for(int i = 0; i < c.length;i++){                primes *= prime[c[i]-'a'];            }            if (table.containsKey(primes)) {                List<String> tmp = table.get(primes);                tmp.add(s);            }            else {                List<String> tmp = new ArrayList<String>();                tmp.add(s);                table.put(primes, tmp);            }        }        Set<Integer> set = table.keySet();        for (Integer s :set) {            List<String> tmp = table.get(s);            r.add(tmp);        }        return r;    }
0 0