Skip to content

Instantly share code, notes, and snippets.

@ozkansari
Last active April 12, 2020 20:34
Show Gist options
  • Save ozkansari/c6437719642a8a6d0820a988bded31f0 to your computer and use it in GitHub Desktop.
Save ozkansari/c6437719642a8a6d0820a988bded31f0 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class GroupAnagrams {
public static void main(String[] args) {
GroupAnagrams problem = new GroupAnagrams();
List<List<String>> result1 = problem.groupAnagrams(new String[] { "eat", "tea", "tan", "ate", "nat", "bat" });
System.out.println("Expected: 6, \n"
+ "Result: " + result1);
}
private static final char PRIMES[] = { 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, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181,
191, 193, 197, 199 };
public List<List<String>> groupAnagrams(String[] wordsArray) {
Map<Integer, List<String>> anagramWords = new HashMap<>();
for (String word : wordsArray) {
Integer key = calculateKey(word);
List<String> wordList = anagramWords.get(key);
if (wordList == null) {
wordList = new ArrayList<String>();
anagramWords.put(key, wordList);
}
wordList.add(word);
}
// return anagramWords.values().stream().collect(Collectors.toCollection(ArrayList::new));
return anagramWords.values().stream().collect(Collectors.toList());
}
private Integer calculateKey(String word) {
// We know word is all lowercase. Otherwise we can convert it to lowercase.
// word = word.toLowerCase();
int key = 1;
for (char letter : word.toCharArray()) {
key *= PRIMES[letter - 'a'];
}
return key;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment