-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroupAnagrams.java
More file actions
40 lines (32 loc) · 1.11 KB
/
GroupAnagrams.java
File metadata and controls
40 lines (32 loc) · 1.11 KB
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
31
32
33
34
35
36
37
38
39
40
package com.leetcode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
/**
* Created by jamylu on 2018/3/28.
* leetcode049
* 给一个字符串数组,将相同字谜组合在一起
*/
public class GroupAnagrams {
public static void main(String[] args) {
String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
System.out.println(group(strs));
}
// 将每个字符串转化为字符数组进行排序
public static List<List<String>> group(String[] strs) {
if (strs == null || strs.length == 0)
return new ArrayList<>();
HashMap<String, List<String>> map = new HashMap<>();
for (String item : strs) {
char[] arrs = item.toCharArray();
Arrays.sort(arrs); // 对字符数组进行排序
String key = String.valueOf(arrs); // 转化为string类型,作为map的key
if (!map.containsKey(key)) {
map.put(key, new ArrayList<>());
}
map.get(key).add(item);
}
return new ArrayList<>(map.values());
}
}