Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Something along the lines of the following code will enable you to get all possibilities (remember to add <code>word</code> itself if needed). The idea is to retreive all possibilities for removing one char (e.g. <code>hello</code> results in <code>ello hllo helo hell</code>). These results can in turn be used to get the possibilities for removing two chars (remove one char again). Resulting in <code>llo elo ell</code> for <code>ello</code> and so on...</p> <pre><code>List&lt;String&gt; getPossibilities(String word) { int removeChars = word.length() - 1; List&lt;String&gt; possibilities = new ArrayList(); List&lt;String&gt; options = Arrays.asList(word); for(int i = 0; i &lt;= removeChars; i++) { List&lt;String&gt; results = new ArrayList(); for(String option : options) { for(String result : removeOneChar(option)) { if(!results.contains(result)) { results.add(result); } } } possibilities.addAll(results); options = results; } return possibilities; } private static List&lt;String&gt; removeOneChar(String word) { List&lt;String&gt; results = new ArrayList(); for(int i = 0; i &lt; word.length(); i++) { int secondPart = i + 2; if(secondPart &lt;= word.length()) { results.add( word.substring(0, i) + word.substring(i + 1, word.length())); } else { results.add( word.substring(0, i)); } } return results; } </code></pre> <p>Notice the <code>if(!contains(result))</code> in order to prevent any duplicates.</p> <p><strong>Note</strong> I've used <code>substring()</code> to accomplish this, you're approach with <code>removeCharAt()</code> is a another good option. You could run some tests to see which performs better to decide which one to use. Notice using the latter could possibly remove the need of the <code>if</code> in the <code>private</code> method.</p>
 

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