Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A simple recursive algorithm can be implemented if you realize that the segmentation of a string <code>s</code> is equal to a set containing <code>s</code> itself, and a set union of each substring <code>X</code> of <code>s</code> with the segmentation of <code>s\X</code>. Also, since you will always have <code>n-1</code> possible substrings, and you can either segment or not segment in each of these points, you will always end up with <code>2^(n-1)</code> segments. </p> <p>It is more simple to understand with an example for the segmentation of the string <code>ABC</code>:</p> <blockquote> <ol> <li>{'ABC'} // 'ABC' itself</li> <li>{'A', 'B, 'C'} // substring 'A' union 1st segmentation of 'BC' = {'B, 'C'}</li> <li>{'A', 'BC'} // substring 'A' union 2nd segmentation of 'BC' = {'BC'}</li> <li>{'AB', 'C'} // substring 'AB' union 1st and only segmentation of 'C' = {'C'}</li> <li>Union of 1, 2, 3, and 4, yield all segmentations of the string <code>ABC</code>.</li> </ol> </blockquote> <p>This translates almost directly to the following implementation:</p> <pre><code>public static Set&lt;Set&lt;String&gt;&gt; segment(String s) { // `s` itself. Set&lt;Set&lt;String&gt;&gt; result = new LinkedHashSet&lt;Set&lt;String&gt;&gt;(); Set&lt;String&gt; root = new LinkedHashSet&lt;String&gt;(); root.add(s); result.add(root); // set union of each substring `X` (prefix) of `s` with `s\X` (rest). for (int i = 1; i &lt; s.length(); i++) { String prefix = s.substring(0, i); String rest = s.substring(i); for (Set&lt;String&gt; segments : segment(rest)) { Set&lt;String&gt; segment = new LinkedHashSet&lt;String&gt;(); segment.add(prefix); segment.addAll(segments); result.add(segment); } } return result; } </code></pre> <p>Sample outputs:</p> <pre><code>System.out.println(segment("ABC")); // [[ABC], [AB, C], [A, B, C], [BC, A]] System.out.println(segment("ABCD")); // [[D, AB, C], [BCD, A], [D, ABC], [D, A, B, C], [AB, CD], [ABCD], [D, BC, A], [A, B, CD]] </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

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