Skip to content

Instantly share code, notes, and snippets.

@Deivur
Created December 25, 2015 10:25
Show Gist options
  • Save Deivur/82c14e79b453209252cc to your computer and use it in GitHub Desktop.
Save Deivur/82c14e79b453209252cc to your computer and use it in GitHub Desktop.
Наибольшее составное слово в массиве. (состоит только из слов, заданных в данном массиве)
import java.util.ArrayList;
import java.util.Comparator;
import java.util.TreeMap;
public class LongestWord {
public static void main(String[] args) {
/* Creation an array of words */
String words[] = { "five", "fivetwo", "fourfive", "fourfivetwo", "one", "onefiveone", "two", "twofivefourone" };
/* Output */
System.out.println("Longest Compound word : " + longestCompundWord(words));
}
/* Method that begins the search the longest a compound word */
private static String longestCompundWord(String[] words) {
/*
* The creation of the storage of all the words and the TreeMap to sort
* the words in ascending order by using a comparator
*/
ArrayList<String> dictionary = new ArrayList<String>();
TreeMap<String, Integer> wordTree = new TreeMap<String, Integer>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
});
/* Put the words from array to the storage and TreeMap */
for (int i = 0; i < words.length; i++) {
wordTree.put(words[i], i);
dictionary.add(words[i]);
}
/* Call next method */
return findLongestCompoundWord(wordTree, dictionary);
}
/*
* Check that the word is really a compound. We look at the contents of the
* word in storage, cut off a letter to the front and back and check the
* presence of parts word in the storage
*/
private static boolean isCompoundWord(String word, ArrayList<String> dictionary) {
if (dictionary.contains(word))
return true;
for (int i = 1; i < word.length(); i++) {
String prefix = word.substring(0, i);
if (isCompoundWord(prefix, dictionary)) {
String remainder = word.substring(i, word.length());
if (remainder.length() == 0)
return true;
return isCompoundWord(remainder, dictionary);
}
}
return false;
}
/*
* Take the longest word from TreeMap and check whether it is a compound.
* Remove this word from the storage and TreeMap
*/
public static String findLongestCompoundWord(TreeMap<String, Integer> wordTree, ArrayList<String> dictionary) {
while (wordTree.size() > 0) {
String word = wordTree.lastKey();
wordTree.remove(word);
dictionary.remove(word);
if (isCompoundWord(word, dictionary))
return word;
}
return "";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment