-
Notifications
You must be signed in to change notification settings - Fork 138
/
Group Anagrams.java
38 lines (33 loc) · 934 Bytes
/
Group Anagrams.java
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
Question:
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Solution:
class Solution {
public List<List<String>> groupAnagrams(String[] string_list) {
List<List<String>> masterList=new ArrayList<>();
Map<String,List<String>> map=new LinkedHashMap<>();
for (String s : string_list) {
char[] si=s.toCharArray();
Arrays.sort(si);
String key=String.valueOf(si);
if(map.containsKey(key)){
map.get(key).add(s);
}else{
List<String> list=new ArrayList<>();
list.add(s);
map.put(key,list);
}
}
for(Map.Entry<String,List<String>> e:map.entrySet()){
masterList.add(e.getValue());
}
return masterList;
}
}