forked from yuanx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnagrams.java
More file actions
49 lines (35 loc) · 1.25 KB
/
Anagrams.java
File metadata and controls
49 lines (35 loc) · 1.25 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.util.Hashtable;
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>();
Hashtable<String,Integer> hash = new Hashtable<String,Integer>();
for(int i=0; i<strs.length; i++){
String sig = signature(strs[i]);
if(hash.containsKey(sig))
hash.put(sig, hash.get(sig)+1);
else
hash.put(sig,1);
}
for(int i=0; i<strs.length; i++){
String sig = signature(strs[i]);
if(hash.get(sig)>1)
result.add(strs[i]);
}
return result;
}
public String signature(String str){
int[] chars = new int[26];
for(int i=0; i<str.length(); i++){
chars[str.charAt(i)-'a'] +=1;
}
String re = "";
for(int i=0; i<26; i++){
for(int j=0; j<chars[i]; j++){
re += (char)(i+97);
}
}
return re;
}
}