From ce5d3a9f8d778e7ce9c01e8dc010611060674689 Mon Sep 17 00:00:00 2001 From: Rohit Bhoompally Date: Thu, 2 Oct 2014 19:48:21 -0400 Subject: [PATCH] Longest compound word using suffix trees. --- solutions/java/LongestCompoundWord.java | 62 +++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 solutions/java/LongestCompoundWord.java diff --git a/solutions/java/LongestCompoundWord.java b/solutions/java/LongestCompoundWord.java new file mode 100644 index 0000000..efcb1a2 --- /dev/null +++ b/solutions/java/LongestCompoundWord.java @@ -0,0 +1,62 @@ +import java.util.ArrayList; +import java.util.HashMap; + +public class LongestCompoundWord { + HashMap suffixTree = new HashMap(); + ArrayList queue = new ArrayList(); + + public static void main(String[] args) { + LongestCompoundWord lcw = new LongestCompoundWord(); + String[] input = { "cat", "cats", "catsdogcats", "catxdogcatsrat", + "dog", "dogcatsdog", "hippopotamuses", "rat", "ratcat", + "ratcatdog", "ratcatdogcat" }; + System.out.println(lcw.getWord(input)); + } + + public String getWord(String[] input) { + String LongestWord = ""; + // First round + for (int i = 0; i < input.length; i++) { + ArrayList suffixes = getSuffixesForPrefixes(input[i], + input[i]); + if (suffixes.size() > 0) { + // Add the pair of original word and suffix to the queue + queue.addAll(suffixes); + } + suffixTree.put(input[i], input[i]); + } + + // Empty the queue while searching for longest word + while (!queue.isEmpty()) { + String[] probePair = queue.get(0); + // Find possible valid and compound words + if (suffixTree.containsKey(probePair[1])) { // Valid word + if (probePair[0].length() > LongestWord.length()) + LongestWord = probePair[0]; + } else { + ArrayList suffixes = getSuffixesForPrefixes( + probePair[0], probePair[1]); + if (suffixes.size() > 0) { + // Add the pair of original word and suffix to the queue + queue.addAll(suffixes); + } + } + queue.remove(0); + } + return LongestWord; + } + + public ArrayList getSuffixesForPrefixes(String originalWord, + String word) { + ArrayList suffixes = new ArrayList(); + for (int i = 1; i <= word.length(); i++) { + if (suffixTree.containsKey(word.substring(0, i))) { + String[] pair = new String[2]; + pair[0] = originalWord; + pair[1] = word.substring(i); + suffixes.add(pair); + } + } + return suffixes; + } +} \ No newline at end of file