-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnagram.java
More file actions
34 lines (28 loc) · 917 Bytes
/
Anagram.java
File metadata and controls
34 lines (28 loc) · 917 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
29
30
31
32
33
34
public class Solution {
public ArrayList<String> anagrams(String[] strs) {
Map<String,List<String>> anagramMap = new HashMap<String, List<String>>();
ArrayList<String> opList = new ArrayList<String>();
if(strs.length <= 1) return opList;
for(String str:strs) {
char[] tempArr = str.toCharArray();
Arrays.sort(tempArr);
String temp = "";
for (int i=0;i<tempArr.length;i++) {
temp += tempArr[i];
}
if(anagramMap.containsKey(temp)) {
List<String> tempList = anagramMap.get(temp);
tempList.add(str);
}else {
List<String> tempList = new ArrayList<String>();
tempList.add(str);
anagramMap.put(temp, tempList);
}
}
for (List<String> strList:anagramMap.values()) {
if(strList.size() <= 1) continue;
for(String str:strList)
opList.add(str);
}
return opList;
}