-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathGroupAnagram.java
More file actions
63 lines (50 loc) · 1.77 KB
/
Copy pathGroupAnagram.java
File metadata and controls
63 lines (50 loc) · 1.77 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
57
58
59
60
61
62
63
/*
* Group anagrams
* https://leetcode.com/problems/group-anagrams/
*/
import java.util.Map;
import java.util.HashMap;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class GroupAnagram {
/**
* @param strs string array
* @return list of list of string
*/
public static List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<Integer>> testMap = new HashMap<>();
int index = 0;
for (String str : strs) {
//TODO: remember how to sort string
char[] strArray = str.toCharArray();
Arrays.sort(strArray);
String newStr = new String(strArray);
if (!testMap.containsKey(newStr) ) {
//TODO: remember how to insert value in ArrayList
testMap.put(newStr, new ArrayList<>(Arrays.asList(index)));
} else {
testMap.get(newStr).add(index);
}
index++;
}
//TODO: remember how to create list of list
List<List<String>> result = new ArrayList<List<String>>();
//TODO: remember how to iterate hashmap
for (Map.Entry<String, List<Integer>> entry : testMap.entrySet()) {
//TODO: remember how to get values
List<Integer> testIndex = entry.getValue();
List<String> tmpString = new ArrayList<String>();
for (int iter : testIndex) {
tmpString.add(strs[iter]);
}
result.add(tmpString);
}
return result;
}
public static void main(String[] args) {
//TODO: remember how to create string array
String[] testInput = {"eat", "tea", "tan", "ate", "nat", "bat"};
System.out.println(groupAnagrams(testInput));
}
}