-
Notifications
You must be signed in to change notification settings - Fork 35
/
GroupAnagramsProg.java
31 lines (26 loc) · 986 Bytes
/
GroupAnagramsProg.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
// GROUP ANAGRAMS (LEETCODE 49) SOLUTION
// Question : https://leetcode.com/problems/group-anagrams/
//--------------------------------------------------------------------------
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if (strs.length == 0)
return new ArrayList();
Map<String, List> ans = new HashMap<String, List>();
int[] count = new int[26];
for (String s : strs) {
Arrays.fill(count, 0);
for (char c : s.toCharArray())
count[c - 'a']++;
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < 26; i++) {
sb.append('#');
sb.append(count[i]);
}
String key = sb.toString();
if (!ans.containsKey(key))
ans.put(key, new ArrayList());
ans.get(key).add(s);
}
return new ArrayList(ans.values());
}
}