Skip to content

Commit c5d2be2

Browse files
authored
Added Solution for LeetCode Problem No. 49
1 parent 676266a commit c5d2be2

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
}

0 commit comments

Comments
 (0)