Skip to content

Commit 807d0da

Browse files
committed
Merge pull request blakeembrey#128 from roitt/longest-compound-word
Longest compound word using suffix trees.
2 parents 6bc7828 + ce5d3a9 commit 807d0da

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import java.util.ArrayList;
2+
import java.util.HashMap;
3+
4+
public class LongestCompoundWord {
5+
HashMap<String, String> suffixTree = new HashMap<String, String>();
6+
ArrayList<String[]> queue = new ArrayList<String[]>();
7+
8+
public static void main(String[] args) {
9+
LongestCompoundWord lcw = new LongestCompoundWord();
10+
String[] input = { "cat", "cats", "catsdogcats", "catxdogcatsrat",
11+
"dog", "dogcatsdog", "hippopotamuses", "rat", "ratcat",
12+
"ratcatdog", "ratcatdogcat" };
13+
System.out.println(lcw.getWord(input));
14+
}
15+
16+
public String getWord(String[] input) {
17+
String LongestWord = "";
18+
// First round
19+
for (int i = 0; i < input.length; i++) {
20+
ArrayList<String[]> suffixes = getSuffixesForPrefixes(input[i],
21+
input[i]);
22+
if (suffixes.size() > 0) {
23+
// Add the pair of original word and suffix to the queue
24+
queue.addAll(suffixes);
25+
}
26+
suffixTree.put(input[i], input[i]);
27+
}
28+
29+
// Empty the queue while searching for longest word
30+
while (!queue.isEmpty()) {
31+
String[] probePair = queue.get(0);
32+
// Find possible valid and compound words
33+
if (suffixTree.containsKey(probePair[1])) { // Valid word
34+
if (probePair[0].length() > LongestWord.length())
35+
LongestWord = probePair[0];
36+
} else {
37+
ArrayList<String[]> suffixes = getSuffixesForPrefixes(
38+
probePair[0], probePair[1]);
39+
if (suffixes.size() > 0) {
40+
// Add the pair of original word and suffix to the queue
41+
queue.addAll(suffixes);
42+
}
43+
}
44+
queue.remove(0);
45+
}
46+
return LongestWord;
47+
}
48+
49+
public ArrayList<String[]> getSuffixesForPrefixes(String originalWord,
50+
String word) {
51+
ArrayList<String[]> suffixes = new ArrayList<String[]>();
52+
for (int i = 1; i <= word.length(); i++) {
53+
if (suffixTree.containsKey(word.substring(0, i))) {
54+
String[] pair = new String[2];
55+
pair[0] = originalWord;
56+
pair[1] = word.substring(i);
57+
suffixes.add(pair);
58+
}
59+
}
60+
return suffixes;
61+
}
62+
}

0 commit comments

Comments
 (0)