-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathAnagram.java
More file actions
43 lines (32 loc) · 1.05 KB
/
Anagram.java
File metadata and controls
43 lines (32 loc) · 1.05 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
package main.java;
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 String word;
public Anagram(String word) {
this.word = word;
}
public 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 sortedWord = sortLetters(this.word);
for (String word: candidates){
String sortedWordMatchingList = sortLetters(word);
if (sortedWord.equals(sortedWordMatchingList) && !this.word.toLowerCase().equals(word.toLowerCase())){
matchingWords.add(word);
}
}
return matchingWords;
}
}