Group Anagrams

LeetCode Q 49 - Group Anagrams

Given an array of strings, group anagrams together.

Solution

Key point is how to identify anagrams.
We can use a prime number to represent each letter in alphabet.
Then use the multiplication of each letter to represent a word.

Code:

private static final int[] KEYS = {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};
public List<List<String>> groupAnagrams(String[] strs) {
	List<List<String>> res = new ArrayList<>();
	if (strs == null || strs.length == 0) return res;

	Map<Integer, List<String>> map = new HashMap<>();
	for (String str: strs) {
		int number = getNumber(str);
		map.putIfAbsent(number, new ArrayList<>());
		map.get(number).add(str);
	}

	for (int num: map.keySet()) 
		res.add(map.get(num));

	return res;
}

private int getNumber(String word) {
	if (word == null || word.length() == 0) return 0;
	int res = 1;
	for (char ch: word.toCharArray())
		res \*= KEYS[ch - 'a'];
	return res;
}

   Reprint policy


《Group Anagrams》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC