-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathAnagram.java
More file actions
39 lines (35 loc) · 1.33 KB
/
Anagram.java
File metadata and controls
39 lines (35 loc) · 1.33 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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
/**
* Given a word and a list of possible anagrams, select the correct sublist.
* Wählen Sie aus einem gegebenen Wort und einer Liste möglicher Anagramme die richtige Teilliste aus.
*
* Given "listen" and a list of candidates like "enlists" "google" "inlets" "banana" the program should return a list containing "inlets".
* Bei "listen" und einer Liste von Kandidaten wie "enlists" "google" "inlets" "banana" sollte das Programm eine Liste mit "inlets" zurückgeben.
*/
public class Anagram {
private final String word;
public Anagram(String word) {
this.word = word;
}
String sortLetters(String word) {
char[] letterArray = word.toLowerCase(Locale.ROOT).toCharArray();
Arrays.sort(letterArray);
return new String(letterArray);
}
public List<String> match(List<String> candidates) {
List<String> matchingWords = new ArrayList<>();
String sortedWords = sortLetters(this.word);
for(String candiate : candidates) {
if(!this.word.toLowerCase(Locale.ROOT).equals(candiate.toLowerCase(Locale.ROOT))) {
String sortedWordToMatch = sortLetters(candiate);
if(sortedWords.equals(sortedWordToMatch)) {
matchingWords.add(candiate);
}
}
}
return matchingWords;
}
}