-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_49_group_anagram.java
More file actions
30 lines (27 loc) · 931 Bytes
/
Copy path_49_group_anagram.java
File metadata and controls
30 lines (27 loc) · 931 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
26
27
28
29
30
import java.util.HashMap;
import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
public class _49_group_anagram {
public List<List<String>> groupAnagrams(String[] strs){
HashMap<String, List<String>> map = new HashMap<>();
for(String s:strs){
char[] c = s.toCharArray();
Arrays.sort(c);
String key = String.valueOf(c);
if(map.containsKey(key)){
map.get(key).add(s);
}
else{
map.put(key, new ArrayList<>(Arrays.asList(s)));
}
}
return new ArrayList<>(map.values());
}
public static void main(String[] args) {
String [] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
_49_group_anagram obj = new _49_group_anagram();
List<List<String>> result = obj.groupAnagrams(strs);
System.out.println(result);
}
}