forked from yuduozhou/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnagrams.java
49 lines (44 loc) · 1.51 KB
/
Anagrams.java
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.util.*;
public class Solution {
public ArrayList<String> anagrams(String[] strs) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<String> result = new ArrayList<String>();
HashMap<String, ArrayList<Integer>> ruler = new HashMap<String, ArrayList<Integer>>();
for (int i = 0; i < strs.length; i ++){
ArrayList<Integer> temp = new ArrayList<Integer>();
String hash = hashWord(strs[i]);
if (ruler.containsKey(hash)){
temp = ruler.get(hash);
}
temp.add(i);
ruler.put(hash, temp);
}
Iterator it = ruler.entrySet().iterator();
while(it.hasNext()) {
Map.Entry me = (Map.Entry)it.next();
ArrayList<Integer> values = (ArrayList<Integer>) me.getValue();
if (values.size() > 1){
for (int index = 0; index < values.size(); index ++){
result.add(strs[values.get(index)]);
}
}
}
return result;
}
public String hashWord(String word){
int[] letters = new int[26];
for (int i = 0; i < 26; i ++) {
letters[i] = 0;
}
for (int i = 0; i < word.length(); i++) {
int index = (int) word.charAt(i) - 97;
letters[index] ++;
}
String result = "";
for (int i: letters){
result += i + "/";
}
return result;
}
}