Skip to content

Instantly share code, notes, and snippets.

@ben-albrecht
Created October 23, 2018 00:52
Show Gist options
  • Save ben-albrecht/b9556766e992b5331c47cbe028cf1f15 to your computer and use it in GitHub Desktop.
Save ben-albrecht/b9556766e992b5331c47cbe028cf1f15 to your computer and use it in GitHub Desktop.
proc lcs(a: string, b: string): string {
var lengths: [1..a.size+1, 1..b.size+1] int;
for (i, x) in zip(1..a.size, a) {
for (j, y) in zip(1..b.size, b) {
if x == y {
lengths[i+1, j+1] = lengths[i, j] + 1;
} else {
lengths[i+1, j+1] = max(lengths[i+1, j], lengths[i, j+1]);
}
}
}
var result = '';
var x = a.size+1,
y = b.size+1;
while x != 1 && y != 1 {
if lengths[x, y] == lengths[x-1, y] then x -= 1;
else if lengths[x, y] == lengths[x, y-1] then y -= 1;
else {
assert(a[x-1] == b[y-1]);
result = a[x-1] + result;
x -= 1;
y -= 1;
}
}
return result;
}
writeln(lcs('1234', '1224533324')); // 1234
writeln(lcs('thisisatest', 'testing123testing')); // tsitest
@ben-albrecht
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment