File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ Time Complexity: O(n)
3+ Space Complexity: O(n)
4+ */
5+ class Solution {
6+ public List <List <String >> groupAnagrams (String [] strs ) {
7+ Map <String , List <String >> map = new HashMap <>();
8+
9+ for (String str : strs ) {
10+ int [] cnt = new int [26 ];
11+ for (int i = 0 ; i < str .length (); i ++) {
12+ cnt [str .charAt (i ) - 'a' ]++;
13+ }
14+ char [] chars = new char [str .length ()];
15+ int idx = 0 ;
16+ for (int i = 0 ; i < 26 ; i ++) {
17+ while (cnt [i ] > 0 ) {
18+ chars [idx ++] = (char )(i + 'a' );
19+ cnt [i ]--;
20+ }
21+ }
22+ String sorted = new String (chars );
23+ if (!map .containsKey (sorted )) {
24+ map .put (sorted , new ArrayList <>());
25+ }
26+ map .get (sorted ).add (str );
27+ }
28+
29+ List <List <String >> ans = new ArrayList <>();
30+ for (String key : map .keySet ()) {
31+ ans .add (new ArrayList <>());
32+ for (String str : map .get (key )) {
33+ ans .get (ans .size () - 1 ).add (str );
34+ }
35+ }
36+
37+ return ans ;
38+ }
39+ }
You can’t perform that action at this time.
0 commit comments