-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathGroupAnagrams.java
More file actions
56 lines (53 loc) · 1.49 KB
/
GroupAnagrams.java
File metadata and controls
56 lines (53 loc) · 1.49 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package leetcode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
/**
* @author eko
* @date 2018/10/22 10:32 AM
*
* Given an array of strings, group anagrams together.
*
* Example:
*
* Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
* Output:
* [
* ["ate","eat","tea"],
* ["nat","tan"],
* ["bat"]
* ]
* Note:
*
* All inputs will be in lowercase.
* The order of your output does not matter.
*/
public class GroupAnagrams {
public static void main(String[] args) {
String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
List<List<String>> res = new GroupAnagrams().groupAnagrams(strs);
System.out.println(res);
}
public List<List<String>> groupAnagrams(String[] strs) {
HashMap<String, List<String>> map = new HashMap<>();
for (int i = 0; i < strs.length; i++) {
char[] chars = strs[i].toCharArray();
Arrays.sort(chars);
StringBuilder sb = new StringBuilder();
for (int j = 0; j < chars.length; j++) {
sb.append(chars[j]);
}
String key = sb.toString();
if (map.containsKey(key)) {
map.get(key).add(strs[i]);
} else {
List<String> str = new ArrayList<>();
str.add(strs[i]);
map.put(key, str);
}
}
List<List<String>> res = new ArrayList<>(map.values());
return res;
}
}