forked from LeBW/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroupAnagrams.java
More file actions
27 lines (25 loc) · 847 Bytes
/
GroupAnagrams.java
File metadata and controls
27 lines (25 loc) · 847 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
import java.util.*;
/**
* 49. Group Anagrams 字母异位词分组
* 哈希
* @author LBW
*/
public class GroupAnagrams {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for (String str: strs) {
char[] cs = str.toCharArray();
Arrays.sort(cs);
String key = String.valueOf(cs);
List<String> l = map.getOrDefault(key, new ArrayList<>());
l.add(str);
map.put(key, l);
}
return new ArrayList<>(map.values());
}
public static void main(String[] args) {
GroupAnagrams groupAnagrams = new GroupAnagrams();
List<List<String>> list = groupAnagrams.groupAnagrams(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"});
System.out.println(list);
}
}