File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+
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
+ }
You can’t perform that action at this time.
0 commit comments