-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathAnagramBuckets.java
66 lines (56 loc) · 1.18 KB
/
AnagramBuckets.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
package algorithms;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
/**
* Prints anagrams in the same bucket.
*
* @author joeytawadrous
*/
public class AnagramBuckets
{
public static void main (String[] args)
{
ArrayList<String> input = new ArrayList<String>();
input.add("star");
input.add("rats");
input.add("ice");
input.add("cie");
input.add("arts");
anagramBuckets(input);
}
/**
* Prints anagrams in the same bucket.
* @param list to sort
*/
public static void anagramBuckets(List<String> input)
{
HashMap<Integer, ArrayList<String>> hashMap = new HashMap<Integer, ArrayList<String>>();
for (String s : input)
{
int hash = 0;
for (int i = 0; i < s.length(); i++)
{
hash += s.charAt(i);
}
if (hashMap.containsKey(hash))
{
ArrayList<String> list = hashMap.get(hash);
list.add(s);
hashMap.put(hash, list);
}
else
{
ArrayList<String> list = new ArrayList<String>();
list.add(s);
hashMap.put(hash, list);
}
}
Set<Integer> keys = hashMap.keySet();
for (Integer key : keys)
{
System.out.println(hashMap.get(key));
}
}
}