-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathAnagram.java
More file actions
36 lines (28 loc) · 967 Bytes
/
Anagram.java
File metadata and controls
36 lines (28 loc) · 967 Bytes
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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
/**
* Given a word and a list of possible anagrams, select the correct sublist.
*
* Given "listen" and a list of candidates like "enlists" "google" "inlets" "banana" the program should return a list containing "inlets".
*/
public class Anagram {
private final String word;
public Anagram(String word) {
this.word = word;
}
public List<String> match(List<String> candidates) {
List<String> foundAnagrams = new ArrayList<>();
char[] wordChars = this.word.toLowerCase().toCharArray();
Arrays.sort(wordChars);
for (String candidate : candidates) {
char[] candidateChars = candidate.toLowerCase().toCharArray();
Arrays.sort(candidateChars);
if(Arrays.equals(wordChars,candidateChars) && !this.word.equalsIgnoreCase(candidate)){
foundAnagrams.add(candidate);
}
}
return foundAnagrams;
}
}