forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_49.java
43 lines (36 loc) · 910 Bytes
/
_49.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 49. Group Anagrams
*
* Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
Note: All inputs will be in lower-case.
*/
public class _49 {
public static class Solution1 {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for (String word : strs) {
char[] c = word.toCharArray();
Arrays.sort(c);
String key = new String(c);
if (!map.containsKey(key)) {
map.put(key, new ArrayList<>());
}
map.get(key).add(word);
}
return new ArrayList<>(map.values());
}
}
}