-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgroupAnagrams.java
More file actions
52 lines (40 loc) · 1.31 KB
/
Copy pathgroupAnagrams.java
File metadata and controls
52 lines (40 loc) · 1.31 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
package LeetCode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class groupAnagrams {
public static List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> hMap = new HashMap<String, List<String>>();
List<List<String>> mainlst = new ArrayList<List<String>>();
Iterator<List<String>> itr;
Iterator<String> itr1;
for (String str : strs) {
String tempStr = str;
char[] chars = tempStr.toCharArray();
Arrays.sort(chars);
String sorted = new String(chars);
if (hMap.get(sorted) == null) {
List<String> subList = new ArrayList<String>();
subList.add(tempStr);
hMap.put(sorted, subList);
} else {
hMap.get(sorted).add(tempStr);
}
}
Iterator it = hMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
// System.out.println(pair.getKey() + " = " + pair.getValue());
mainlst.add((List<String>) pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
return mainlst;
}
public static void main(String[] args) {
String[] str = { "eat", "tea", "tan", "ate", "nat", "bat" };
List<List<String>> res = groupAnagrams(str);
}
}