File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public List <List <String >> groupAnagrams (String [] strs ) {
3+ int [][] alphabets = new int [strs .length ]['z' - 'a' + 1 ];
4+
5+ for (int i = 0 ; i < strs .length ; i ++) {
6+ String str = strs [i ];
7+
8+ for (int j = 0 ; j < str .length (); j ++)
9+ alphabets [i ][str .charAt (j ) - 'a' ]++;
10+ }
11+
12+ boolean [] visited = new boolean [strs .length ];
13+
14+ List <List <String >> answer = new ArrayList <>();
15+
16+ for (int i = 0 ; i < strs .length ; i ++) {
17+ if (visited [i ]) continue ;
18+
19+ List <String > list = new ArrayList <>();
20+
21+ for (int j = i ; j < strs .length ; j ++) {
22+ if (visited [j ]) continue ;
23+ if (isAnagram (alphabets [i ], alphabets [j ])) {
24+ list .add (strs [j ]);
25+ visited [j ] = true ;
26+ }
27+ }
28+
29+ answer .add (list );
30+ }
31+
32+ return answer ;
33+ }
34+
35+ public boolean isAnagram (int [] arr1 , int [] arr2 ) {
36+ for (int i = 0 ; i < arr1 .length ; i ++) {
37+ if (arr1 [i ] != arr2 [i ])
38+ return false ;
39+ }
40+ return true ;
41+ }
42+ }
You can’t perform that action at this time.
0 commit comments