-
Notifications
You must be signed in to change notification settings - Fork 37
/
49 Group Anagrams
40 lines (29 loc) · 1015 Bytes
/
49 Group 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
36
37
38
39
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> result = new ArrayList();
HashMap<String,List<String>> map = new HashMap();
//["eat", "tea", "tan", "ate", "nat", "bat"]
for(int i=0;i<strs.length;i++){
char[] characters = strs[i].toCharArray(); //e a t
Arrays.sort(characters); // a e t
String sorted = new String(characters);//aet -- eat
if(!map.containsKey(sorted)){
map.put(sorted,new ArrayList());
}
map.get(sorted).add(strs[i]);
}
result.addAll(map.values());
return result;
}
//HasHMap<String,List<String>>
//aet , List<eat,tea,ate>
//ant , List<tan,nat>
//abt , List<bat>