-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGroupe Anagrams
35 lines (31 loc) · 1.24 KB
/
Groupe Anagrams
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
class Solution {
HashMap<String, List<String>> hashmap = new HashMap<>();
public List<List<String>> groupAnagrams(String[] strs) {
for(String str : strs){
List<String> replacementList = new ArrayList<String>();
String sortedStr = sortString(str);
if(hashmap.containsKey(sortedStr)){
replacementList = hashmap.get(sortedStr);
replacementList.add(str);
hashmap.put(sortedStr, replacementList);
}else{
replacementList.add(str);
hashmap.put(sortedStr, replacementList);
}
}
return hashmapToArray(hashmap);
}
private List<List<String>> hashmapToArray(HashMap<String, List<String>> hashmap){
List<List<String>> result = new ArrayList<List<String>>();
for (Map.Entry<String, List<String>> entry : hashmap.entrySet()) {
System.out.print("(" + entry.getKey() + "," + entry.getValue() + ") ");
result.add((List<String>)entry.getValue());
}
return result;
}
private String sortString(String str){
char[] chars = str.toCharArray();
Arrays.sort(chars);
return new String(chars);
}
}