Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's a (lightly-tested) version of code that does what you asked. You can easily traverse the result in parallel with the inputs to locate insertions and deletions.</p> <pre><code>public class StringDiff { private static int length(String s) { return s == null ? 0 : s.length(); } private static char[] chars(String s) { return s == null ? new char[0] : s.toCharArray(); } private final String left; private final String right; private final char[] lccs; private final String lcs; public StringDiff(String left, String right) { this.left = left; this.right = right; lccs = init(); lcs = new String(lccs); } public String getLcs() { return lcs; } public char[] getLccs() { return lccs.clone(); } private char[] init() { int lLength = length(left); int rLength = length(right); char[] lChars = chars(left); char[] rChars = chars(right); int [][] t = new int [lLength + 1][rLength + 1]; for (int i = lLength - 1; i &gt;= 0; --i) { for (int j = rLength - 1; j &gt;= 0; --j) { if (lChars[i] == rChars[j]) { t[i][j] = t[i + 1][j + 1] + 1; } else { t[i][j] = Math.max(t[i + 1][j], t[i][j + 1]); } } } char[] result = new char[t[0][0]]; int l = 0, r = 0, p = 0; while (l &lt; lLength &amp;&amp; r &lt; rLength) { if (lChars[l] == rChars[r]) { result[p++] = lChars[l++]; r++; } else { if (t[l + 1][r] &gt; t[l][r + 1]) { ++l; } else { ++r; } } } return result; } } </code></pre> <p>According to it, the actual longest subsequence of your original inputs:</p> <pre><code>The quick brown fox jumped over the lazy dog. The quick yellow fox jumped over the well-bred dog. </code></pre> <p>is:</p> <pre><code>The quick ow fox jumped over the l dog. </code></pre> <p>(because "brown" and "yellow" have "ow" in common, etc.)</p> <p>It's relatively straightforward to modify the above to split on whitespace (instead of into char arrays) and substitute String#equals for == to get a version that finds the longest common subsequence of words instead of characters. For your example above that change would produce the obvious result:</p> <pre><code>found 7 words 'The' 'quick' 'fox' 'jumped' 'over' 'the' 'dog.' </code></pre> <p>(Your question implied character comparisons, as you matched the spaces between words.)</p>
    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. 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