-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnagram.java
More file actions
67 lines (52 loc) · 1.38 KB
/
Anagram.java
File metadata and controls
67 lines (52 loc) · 1.38 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class Anagram {
public static void main(String[] args){
String[] strs = {"","b","ab","ba"};
ArrayList<String> a = anagrams(strs);
System.out.println(a);
String b = "sa";
if(b.matches("s.")){
System.out.println("regex here!");
}
}
public static ArrayList<String> anagrams(String[] strs) {
List<String> strslist = new LinkedList<String>(Arrays.asList(strs));
ArrayList<String> all = new ArrayList<String>();
while(strslist.size()>1){
boolean hasanagram = false;
int i =1;
while(i< strslist.size()){
if(isanagram(strslist.get(0), strslist.get(i))){
if(!hasanagram){
all.add(strslist.remove(i));
hasanagram = true;
continue;
}
else{
all.add(strslist.remove(i));
continue;
}
}
i++;
}
if(hasanagram){
all.add(strslist.remove(0));
}else{
strslist.remove(0);
}
}
return all;
}
public static boolean isanagram(String str1, String str2){
char[] str1arr = str1.toCharArray();
char[] str2arr = str2.toCharArray();
Arrays.sort(str1arr);
Arrays.sort(str2arr);
String str1new = new String(str1arr);
String str2new = new String(str2arr);
return str1new.equals(str2new);
}
}