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