File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed
LeetCode/49. Group Anagrams Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
1
+ // https://leetcode.com/problems/group-anagrams/
2
+
3
+ class Solution {
4
+ public List <List <String >> groupAnagrams (String [] s ) {
5
+ if (s .length == 1 ) {
6
+ List <String > list = new ArrayList <>(1 );
7
+ list .add (s [0 ]);
8
+ List <List <String >> res = new ArrayList <>(1 );
9
+ res .add (list );
10
+ return res ;
11
+ }
12
+ Map <String , List <String >> map = new HashMap <>();
13
+ for (String word : s ) {
14
+ char [] alphabet = new char [26 ];
15
+ for (char c : word .toCharArray ()) {
16
+ alphabet [c - 'a' ]++;
17
+ }
18
+ String key = new String (alphabet );
19
+ if (map .containsKey (key )) {
20
+ map .get (key ).add (word );
21
+ } else {
22
+ List <String > list = new ArrayList <>();
23
+ list .add (word );
24
+ map .put (key ,list );
25
+ }
26
+ }
27
+ return new ArrayList <>(map .values ());
28
+ }
29
+ }
You can’t perform that action at this time.
0 commit comments