forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanagrams.java
More file actions
executable file
·28 lines (26 loc) · 896 Bytes
/
anagrams.java
File metadata and controls
executable file
·28 lines (26 loc) · 896 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
28
public class Solution {
public ArrayList<String> anagrams(String[] strs) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<String> ans = new ArrayList<String>();
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
for(String e : strs ){
char[] chare1 = e.toCharArray();
Arrays.sort(chare1);
String chare = new String(chare1);
if(map.keySet().contains(chare)){
map.get(chare).add(e);
}else{
ArrayList<String> al = new ArrayList<String>();
al.add(e);
map.put(chare, al);
}
}
for(String e : map.keySet()){
if(map.get(e).size()>1){
ans.addAll(map.get(e));
}
}
return ans;
}
}