-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathAnagrams (Raymond Li)
More file actions
48 lines (47 loc) · 1.27 KB
/
Anagrams (Raymond Li)
File metadata and controls
48 lines (47 loc) · 1.27 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
public class Solution {
class compareStr implements Comparator<String>{
public int compare(String s1, String s2){
char[] arr1 = s1.toCharArray();
char[] arr2 = s2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
String s3 = "";
String s4 = "";
int i = 0;
while(i<arr1.length){
s3 += arr1[i];
i++;
}
i = 0;
while(i<arr2.length){
s4 += arr2[i];
i++;
}
return s3.compareTo(s4);
}
}
public List<String> anagrams(String[] strs) {
List<String> res = new ArrayList<String>();
if(strs.length<2){
return res;
}
Arrays.sort(strs, new compareStr());
compareStr c = new compareStr();
int j = 0;
int i = 0;
while(i<strs.length-1){
if(c.compare(strs[i],strs[i+1])==0){
j = i;
while(j<strs.length&&c.compare(strs[j],strs[i])==0){
res.add(strs[j]);
j++;
}
i = j;
}
else{
i++;
}
}
return res;
}
}