-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnagrams.java
More file actions
23 lines (22 loc) · 774 Bytes
/
Anagrams.java
File metadata and controls
23 lines (22 loc) · 774 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 Anagrams {
public ArrayList<String> anagrams(String[] strs) {
ArrayList<String> anagram = new ArrayList<String>();
HashMap<String,ArrayList<String>> list = new HashMap<String,ArrayList<String>>();
for (String str: strs) {
char[] chars = str.toCharArray();
Arrays.sort(chars);
String key = new String(chars);
if (list.containsKey(key)) {
list.get(key).add(str);
} else {
list.put(key,new ArrayList<String>(Arrays.asList(str)));
}
}
for (ArrayList<String> test:list.values()) {
if (test.size() > 1) {
anagram.addAll(test);
}
}
return anagram;
}
}