1
+ /*
2
+ Author: King, wangjingui@outlook.com
3
+ Date: Dec 25, 2014
4
+ Problem: Anagrams
5
+ Difficulty: Easy
6
+ Source: https://oj.leetcode.com/problems/anagrams/
7
+ Notes:
8
+ Given an array of strings, return all groups of strings that are anagrams.
9
+ Note: All inputs will be in lower-case.
10
+
11
+ Solution: Sort the string to see if they're anagrams.
12
+ */
13
+
14
+ import java .util .Map .Entry ;
15
+ public class Solution {
16
+ public List <String >anagrams (String []strs ) {
17
+ ArrayList <String >res =new ArrayList <String >();
18
+ HashMap <String ,ArrayList <String >>group =new HashMap <String ,ArrayList <String >>();
19
+ if (strs .length ==0 )return res ;
20
+ for (int i =0 ;i <strs .length ; ++i ) {
21
+ char []tmp =strs [i ].toCharArray ();
22
+ Arrays .sort (tmp );
23
+ String s =String .valueOf (tmp );
24
+ if (group .containsKey (s ))
25
+ (group .get (s )).add (strs [i ]);
26
+ else {
27
+ ArrayList <String >t =new ArrayList <String >();
28
+ t .add (strs [i ]);
29
+ group .put (s ,t );
30
+ }
31
+ }
32
+ Iterator <Entry <String ,ArrayList <String >>>iter =group .entrySet ().iterator ();
33
+ while (iter .hasNext ()) {
34
+ Map .Entry entry = (Map .Entry )iter .next ();
35
+ ArrayList <String >val = (ArrayList <String >)entry .getValue ();
36
+ if (val .size () >1 )res .addAll (val );
37
+ }
38
+ return res ;
39
+ }
40
+ }