forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGroup Anagrams.java
36 lines (36 loc) · 1.01 KB
/
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
// Runtime: 16 ms (Top 40.82%) | Memory: 46.2 MB (Top 88.53%)
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
HashMap<String,ArrayList<String>> hm=new HashMap<>();
for(String s : strs)
{
char ch[]=s.toCharArray();
Arrays.sort(ch);
StringBuilder sb=new StringBuilder("");
for(char c: ch)
{
sb.append(c);
}
String str=sb.toString();
if(hm.containsKey(str))
{
ArrayList<String> temp=hm.get(str);
temp.add(s);
hm.put(str,temp);
}
else
{
ArrayList<String> temp=new ArrayList<>();
temp.add(s);
hm.put(str,temp);
}
}
System.out.println(hm);
List<List<String>> res=new ArrayList<>();
for(ArrayList<String> arr : hm.values())
{
res.add(arr);
}
return res;
}
}