-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy path49.group-anagrams.java
More file actions
65 lines (60 loc) · 1.32 KB
/
49.group-anagrams.java
File metadata and controls
65 lines (60 loc) · 1.32 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
* @lc app=leetcode id=49 lang=java
*
* [49] Group Anagrams
*
* https://leetcode.com/problems/group-anagrams/description/
*
* algorithms
* Medium (46.25%)
* Likes: 1856
* Dislikes: 120
* Total Accepted: 370.8K
* Total Submissions: 768.1K
* Testcase Example: '["eat","tea","tan","ate","nat","bat"]'
*
* Given an array of strings, group anagrams together.
*
* Example:
*
*
* Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
* Output:
* [
* ["ate","eat","tea"],
* ["nat","tan"],
* ["bat"]
* ]
*
* Note:
*
*
* All inputs will be in lowercase.
* The order of your output does not matter.
*
*
*/
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if (strs.length == 0) return new ArrayList();
Map<String, List<String>> map = new HashMap<>();
int[] count = new int[26];
for (String str : strs) {
Arrays.fill(count, 0);
for (char ch : str.toCharArray()) {
count[ch - 'a']++;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < count.length; i++) {
sb.append("#");
sb.append(count[i]);
}
String key = sb.toString();
if (!map.containsKey(key)) {
map.put(key, new ArrayList());
}
map.get(key).add(str);
}
return new ArrayList(map.values());
}
}