1
+ package Algorithms .hash ;
2
+
3
+ import java .util .ArrayList ;
4
+ import java .util .Arrays ;
5
+ import java .util .HashMap ;
6
+ import java .util .List ;
7
+ import java .util .Map ;
8
+
9
+ public class Anagrams {
10
+ public List <String >anagrams (String []strs ) {
11
+ List <String >ret =new ArrayList <String >();
12
+
13
+ if (strs ==null ) {
14
+ return ret ;
15
+ }
16
+
17
+ HashMap <String ,List <String >>map =new HashMap <String ,List <String >>();
18
+
19
+ int len =strs .length ;
20
+ for (int i =0 ;i <len ;i ++) {
21
+ String s =strs [i ];
22
+
23
+ // Sort the string.
24
+ char []chars =s .toCharArray ();
25
+ Arrays .sort (chars );
26
+ String strSort =new String (chars );
27
+
28
+ // Create a ArrayList for the sorted string.
29
+ if (!map .containsKey (strSort )) {
30
+ map .put (strSort ,new ArrayList <String >());
31
+ }
32
+
33
+ // Add a new string to the list of the hashmap.
34
+ map .get (strSort ).add (s );
35
+ }
36
+
37
+ // go through the map and add all the strings into the result.
38
+ for (Map .Entry <String ,List <String >>entry :map .entrySet ()) {
39
+ List <String >list =entry .getValue ();
40
+
41
+ // skip the entries which only have one string.
42
+ if (list .size () ==1 ) {
43
+ continue ;
44
+ }
45
+
46
+ // add the strings into the list.
47
+ ret .addAll (list );
48
+ }
49
+
50
+ return ret ;
51
+ }
52
+ }