File tree Expand file tree Collapse file tree
LeetCodePrj/Java/leetcode/medium/page1 Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package leetcode .medium .page1 ;
2+
3+ import java .util .*;
4+
5+ public class GroupAnagrams {
6+ public List <List <String >> groupAnagrams (String [] strs ) {
7+ List <List <String >> res = new ArrayList <>(strs .length );
8+ int count = 0 ;
9+
10+ int [] flag = new int [strs .length ];
11+
12+ for (int i = 0 ; i < strs .length ; i ++) {
13+ if (flag [i ] == 1 ) {
14+ continue ;
15+ }
16+ List <String > curGroup = new LinkedList <>();
17+ curGroup .add (strs [i ]);
18+
19+ Map <Character , Integer > iFeature = new HashMap <>(strs [i ].length ());
20+ for (int f = 0 ; f < strs [i ].length (); f ++) {
21+ iFeature .put (strs [i ].charAt (f ), iFeature .getOrDefault (strs [i ].charAt (f ), 0 ) + 1 );
22+ }
23+
24+ for (int j = i + 1 ; j < strs .length ; j ++) {
25+ if (strs [i ].length () != strs [j ].length ()) {
26+ continue ;
27+ }
28+
29+ boolean sameGroup = true ;
30+ Map <Character , Integer > jFeature = new HashMap <>(strs [j ].length ());
31+ for (int f = 0 ; f < strs [j ].length (); f ++) {
32+ jFeature .put (strs [j ].charAt (f ), jFeature .getOrDefault (strs [j ].charAt (f ), 0 ) + 1 );
33+ }
34+
35+ if (iFeature .size () != jFeature .size ()) {
36+ sameGroup = false ;
37+ } else {
38+ for (Map .Entry entry : iFeature .entrySet ()) {
39+ if (jFeature .get (entry .getKey ()) != entry .getValue ()) {
40+ sameGroup = false ;
41+ break ;
42+ }
43+ }
44+ }
45+
46+ if (sameGroup ) {
47+ curGroup .add (strs [j ]);
48+ flag [j ] = 1 ;
49+ }
50+ }
51+
52+ res .add (curGroup );
53+ count ++;
54+ }
55+
56+ return res ;
57+ }
58+ }
You can’t perform that action at this time.
0 commit comments