forked from exercism/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnagram.java
More file actions
48 lines (35 loc) · 1.18 KB
/
Anagram.java
File metadata and controls
48 lines (35 loc) · 1.18 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
import java.util.*;
public class Anagram {
private final AnagramSubject anagramSubject;
public Anagram(String word) {
anagramSubject = new AnagramSubject(word);
}
public List<String> match(List<String> candidates) {
List<String> anagrams = new ArrayList<String>();
for (String candidate : candidates) {
if (anagramSubject.anagramOf(candidate)) {
anagrams.add(candidate);
}
}
return anagrams;
}
static final class AnagramSubject {
private final String word;
private final char[] fingerprint;
public AnagramSubject(String other) {
this.word = other;
this.fingerprint = canonicalize(other);
}
public boolean anagramOf(String other) {
return !duplicate(other) && Arrays.equals(fingerprint,canonicalize(other));
}
private boolean duplicate(String other) {
return word.equalsIgnoreCase(other);
}
private char[] canonicalize(String other) {
char[] chars = other.toLowerCase().toCharArray();
Arrays.sort(chars);
return chars;
}
}
}