forked from gouthampradhan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GroupAnagrams.java
72 lines (63 loc) · 1.81 KB
/
GroupAnagrams.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package hashing;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
/**
* Created by gouthamvidyapradhan on 10/03/2017.
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
Note: All inputs will be in lower-case.
*/
public class GroupAnagrams
{
private int[] A = new int[256];
private HashMap<String, List<String>> hashMap = new HashMap<>();
private List<List<String>> result = new ArrayList<>();
/**
* Main method
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
String[] strs = {"huh", "tit"};
List<List<String>> result = new GroupAnagrams().groupAnagrams(strs);
for (List<String> l : result)
{
for(String s : l)
System.out.println(s);
System.out.println("-----");
}
}
public List<List<String>> groupAnagrams(String[] strs)
{
for(int i = 0, l = strs.length; i < l; i ++)
{
Arrays.fill(A, 0);
String s = strs[i];
for(int j = 0, sl = s.length(); j < sl; j ++)
A[s.charAt(j)]++;
StringBuilder sb = new StringBuilder();
for(int k = 0; k < 256; k ++)
{
if(A[k] != 0)
sb.append(k).append("").append(A[k]);
}
List<String> value = hashMap.get(sb.toString());
if(value == null)
value = new ArrayList<>();
value.add(s);
hashMap.put(sb.toString(), value);
}
for(String s : hashMap.keySet())
result.add(hashMap.get(s));
return result;
}
}