Problem:
Given a group of words, return the grouped anagrams.For example, given {"pea", "tea", "ate", "ape", "eat", "root"}
the output should be
{
{"eat", "tea", "ate"},
{"ape", "pea"},
{"root"}
}
solution:
The anagrams has the same characters, once sorted, they become the same string. We can group them with a hashMap.
import java.util.*;
class Anagrams {
private static void getAnagrams(String[] words) {
Map<String, Set<String>> groups = new HashMap<>();
for(String word : words) {
char[] chars = word.toCharArray();
Arrays.sort(chars);
String tmp = new String(chars);
if(groups.get(tmp) == null) {
Set<String> group = new HashSet<>();
group.add(word);
groups.put(tmp, group);
} else {
groups.get(tmp).add(word);
}
}
groups.values().forEach(System.out::println);
}
public static void main(String...args) {
String[] words = new String[] {"pea", "tea", "ate", "ape", "eat", "root"};
getAnagrams(words);
}
}
we iterate the words list cost N, sort each word cost logw, w is the length of the word, so the time complexity is O(NlogW), the space complexity is O(N).
class Anagrams {
private static void getAnagrams(String[] words) {
Map<String, Set<String>> groups = new HashMap<>();
for(String word : words) {
char[] chars = word.toCharArray();
Arrays.sort(chars);
String tmp = new String(chars);
if(groups.get(tmp) == null) {
Set<String> group = new HashSet<>();
group.add(word);
groups.put(tmp, group);
} else {
groups.get(tmp).add(word);
}
}
groups.values().forEach(System.out::println);
}
public static void main(String...args) {
String[] words = new String[] {"pea", "tea", "ate", "ape", "eat", "root"};
getAnagrams(words);
}
}