Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here you go. The mash-method will find a solution (list of dictionary words) for any given String using a dictionary passed to the constructor. If there's no solution (ending to a one letter word), the method will return null. If you are interested in all partial solutions (ending before getting to a one letter word), you should tweak the algorithm a bit.</p> <p>The dictionary is assumed to be a set of uppercase Strings. You could of course use your own class/interface instead.</p> <pre><code>import java.util.ArrayList; import java.util.List; import java.util.Set; public class WordMash { private final Set&lt;String&gt; dictionary; public WordMash(Set&lt;String&gt; dictionary) { if (dictionary == null) throw new IllegalArgumentException("dictionary == null"); this.dictionary = dictionary; } public List&lt;String&gt; mash(String word) { return recursiveMash(new ArrayList&lt;String&gt;(), word.toUpperCase()); } private List&lt;String&gt; recursiveMash(ArrayList&lt;String&gt; wordStack, String proposedWord) { if (!dictionary.contains(proposedWord)) { return null; } wordStack.add(proposedWord); if (proposedWord.length() == 1) { return wordStack; } for (int i = 0; i &lt; proposedWord.length(); i++) { String nextProposedWord = proposedWord.substring(0, i) + proposedWord.substring(i + 1, proposedWord.length()); List&lt;String&gt; finalStack = recursiveMash(wordStack, nextProposedWord); if (finalStack != null) return finalStack; } return null; } } </code></pre> <p>Example:</p> <pre><code>Set&lt;String&gt; dictionary = new HashSet&lt;String&gt;(Arrays.asList( "A", "AFRICA", "AN", "LANE", "PAN", "PANT", "PLANET", "PLANT" )); WordMash mash = new WordMash(dictionary); System.out.println(mash.mash("planet")); System.out.println(mash.mash("pant")); System.out.println(mash.mash("foo")); System.out.println(mash.mash("lane")); System.out.println(mash.mash("africa")); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload