This commit is contained in:
Ingy döt Net 2013-04-10 21:29:02 -07:00
parent 764da6cbbb
commit db842d013d
19005 changed files with 197040 additions and 7 deletions

View file

@ -0,0 +1,13 @@
import std.stdio;
T[] lcs(T)(in T[] a, in T[] b) pure nothrow {
if (!a.length || !b.length) return null;
if (a[0] == b[0])
return a[0] ~ lcs(a[1 .. $], b[1 .. $]);
auto l1 = lcs(a, b[1 .. $]), l2 = lcs(a[1 .. $], b);
return l1.length > l2.length ? l1 : l2;
}
void main() {
writeln(lcs("thisisatest", "testing123testing"));
}

View file

@ -0,0 +1,30 @@
import std.stdio, std.algorithm, std.traits;
T[] lcs(T)(in T[] a, in T[] b) pure /*nothrow*/ {
auto L = new int[][](a.length + 1, b.length + 1);
Unqual!T[] result;
int i, j;
for (i = 0; i < a.length; i++)
for (j = 0; j < b.length; j++)
L[i+1][j+1] = (a[i] == b[j]) ? (1 + L[i][j]) :
max(L[i+1][j], L[i][j+1]);
while (i > 0 && j > 0)
if (a[i - 1] == b[j - 1]) {
result ~= a[i - 1];
i--;
j--;
} else
if (L[i][j - 1] < L[i - 1][j])
i--;
else
j--;
result.reverse(); // not nothrow
return result;
}
void main() {
writeln(lcs("thisisatest", "testing123testing"));
}