-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAnagrams.java
More file actions
23 lines (22 loc) · 772 Bytes
/
Anagrams.java
File metadata and controls
23 lines (22 loc) · 772 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Solution {
public ArrayList<String> anagrams(String[] strs) {
HashMap<String, ArrayList<String>> map =
new HashMap<String, ArrayList<String>>();
for (int i = 0; i < strs.length; ++i) {
char[] c = strs[i].toCharArray();
Arrays.sort(c);
String key = new String(c);
if (!map.containsKey(key)) {
map.put(key, new ArrayList<String>());
}
map.get(key).add(strs[i]);
}
ArrayList<String> result = new ArrayList<String>();
for (ArrayList<String> val : map.values()) {
if (val.size() > 1) {
result.addAll(val);
}
}
return result;
}
}