-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathAnagram.java
More file actions
38 lines (31 loc) · 1.02 KB
/
Anagram.java
File metadata and controls
38 lines (31 loc) · 1.02 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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 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;
}
String sortLetters(String word) {
char[] letterArray = word.toLowerCase().toCharArray();
Arrays.sort(letterArray);
String sorted = new String(letterArray);
return sorted;
}
public List<String> match(List<String> candidates) {
List<String> matchingWords = new ArrayList<String>();
String sortedWord = sortLetters(this.word);
for (String word : candidates) {
String sortedWordToMatch = sortLetters(word);
if (sortedWord.equals(sortedWordToMatch) && !this.word.toLowerCase().equals(word.toLowerCase())) {
matchingWords.add(word);
}
}
return matchingWords;
}
}