### 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:

• For the return value, each inner list's elements must follow the lexicographic order.
• All inputs will be in lower-case.

``````import java.util.*;
/**
* Created by gzdaijie on 16/5/23
* 不同的质数相乘，结果一定不同，可以用不同质数代替字母
* 判断乘积，即可以判断是否属于同一组，借助hashMap记录键值对
*/
public class Solution {
public static List<List<String>> groupAnagrams(String[] strs) {
int[] prime = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103};
List<List<String>> result = new ArrayList<>();
HashMap<Integer, Integer> hash = new HashMap<>();

for (String s : strs) {
int key = 1;
for (char ch: s.toCharArray()) {
key *= prime[ch - 'a'];
}

if (hash.containsKey(key)) {
result.get(hash.get(key)).add(s);
} else {
List<String> t = new ArrayList<>();
t.add(s);
result.add(t);
hash.put(key, result.size() - 1);
}
}

for (List list: result) {
Collections.sort(list);
}
return result;
}
}
``````
updated 2016-05-23 23:08:40