-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGroupAnagrams.java
More file actions
25 lines (22 loc) · 861 Bytes
/
GroupAnagrams.java
File metadata and controls
25 lines (22 loc) · 861 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package swe.Strings;
import java.util.*;
public class GroupAnagrams {
public List<List<String>> groupAnagrams(String[] words) {
Map<String,List<String>> map = new HashMap<>();
for ( String word: words) {
char[] chars = word.toCharArray();
Arrays.sort(chars);
String signature = new String(chars);
List<String> anagram = map.getOrDefault(signature,new ArrayList<>());
anagram.add(word);
map.put(signature,anagram);
}
return new ArrayList<>(map.values());
}
public static void main(String[] args) {
String[] words = {"eat", "tea", "tan", "ate", "nat", "bat"};
GroupAnagrams ga = new GroupAnagrams();
List<List<String>> result = ga.groupAnagrams(words);
System.out.println(result);
}
}