-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLeetCode-49-Group-Anagrams.java
More file actions
33 lines (28 loc) · 956 Bytes
/
LeetCode-49-Group-Anagrams.java
File metadata and controls
33 lines (28 loc) · 956 Bytes
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
/*
LeetCode: https://leetcode.com/problems/anagrams/
LintCode: http://www.lintcode.com/problem/anagrams/
JiuZhang: http://www.jiuzhang.com/solutions/anagrams/
ProgramCreek: http://www.programcreek.com/2014/04/leetcode-anagrams-java/
Analysis:
Using HashMap as map.
*/
public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> result = new ArrayList<>();
Map<String, List<String>> map = new HashMap<>();
for (String str : strs) {
String formatted = formatStr(str);
map.putIfAbsent(formatted, new ArrayList<>());
map.get(formatted).add(str);
}
for(List<String> l : map.values()) {
result.add(l);
}
return result;
}
private String formatStr(String str) {
char[] chars = str.toCharArray();
Arrays.sort(chars);
return new String(chars);
}
}