-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathExample17.java
100 lines (71 loc) · 2.48 KB
/
Example17.java
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package applications.algorithms;
import java.util.*;
/** Category: Algorithms
* ID: Example 17
* Description: Given a list of words get all the anagrams of a given string
* Taken From:
* Details:
* TODO
*/
public class Example17 {
public static List<String> getAnagrams(List<String> words, String a){
if(words == null || a == null){
throw new NullPointerException("Either list of words or word is null");
}
//create a Map with the signatures of the words
Map<String, List<String>> wordSignature = new HashMap<>();
for(String word : words){
char[] arr = word.toLowerCase().toCharArray();
Arrays.sort(arr);
String sorted = new String(arr);
if(wordSignature.containsKey(sorted)){
wordSignature.get(sorted).add(word);
}
else{
List<String> newList = new ArrayList<String>();
newList.add(word);
wordSignature.put(sorted, newList);
}
}
// now that we sorted the words find the signature
// of our word
char[] arr = a.toLowerCase().toCharArray();
Arrays.sort(arr);
String sorted = new String(arr);
if(wordSignature.containsKey(sorted)){
return wordSignature.get(sorted);
}
List<String> list = new ArrayList<>();
return list;
}
public static void main(String[] args){
List<String> words = new ArrayList<>();
words.add("eve");
words.add("test");
words.add("abba");
words.add("efkllkfe");
words.add("aaa");
words.add("AAA");
words.add("aba");
words.add("aBA");
words.add("emnnme");
String a = "ABA";
List<String> wordAnagrams = Example17.getAnagrams(words, a);
System.out.println("Word "+a+" is the anagram of "+wordAnagrams.size()+ " words...");
if(wordAnagrams.size() != 0){
System.out.println("...these are");
for (String s: wordAnagrams) {
System.out.println(s);
}
}
a = "Alex";
wordAnagrams = Example17.getAnagrams(words, a);
System.out.println("Word "+a+" is the anagram of "+wordAnagrams.size()+ " words...");
if(wordAnagrams.size() != 0){
System.out.println("...these are");
for (String s: wordAnagrams) {
System.out.println(s);
}
}
}
}