-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnagrams.java
More file actions
33 lines (26 loc) · 1.03 KB
/
Anagrams.java
File metadata and controls
33 lines (26 loc) · 1.03 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
public class Anagrams {
public List<String> anagrams(String[] strs) {
ArrayList<String> ret = new ArrayList<String> ();
if(strs == null || strs.length ==0) return ret;
HashMap<String, ArrayList<String>> temp = new HashMap<String, ArrayList<String>>();
for( int i=0; i<strs.length; i++) {
char[] str = strs[i].toCharArray();
Arrays.sort(str);
String key = new String(str);
if(temp.containsKey(key)) {
temp.get(key).add(strs[i]);
} else {
ArrayList<String> stringList = new ArrayList<String> ();
stringList.add(strs[i]);
temp.put(key, stringList);
}
}
Iterator<ArrayList<String>> it = temp.values().iterator();
while(it.hasNext()) {
ArrayList<String> stringList = it.next();
if(stringList.size()>1)
ret.addAll(stringList);
}
return ret;
}
}