If you just want to use brute force then using a hash is really cheating as it is already the begining of optimisation. We need nasty embedded loops to go O(2^n*2^m). I think something like this represents to worst way to do it, first generating all possible subsequences and then testing every case. This does however seem to be the point.
use strict; sub subseqs { my $str = $_[0]; my @seqs = (''); for my $char (split //, $str) { for my $i ( 0..@seqs-1 ) { push @seqs, $seqs[$i].$char; } } return @seqs; } my $s1 = 'abcdefgh'; my $s2 = 'abecdgh'; my $best_len = 0; my $longest; for my $seq1 (subseqs($s1)) { for my $seq2 (subseqs($s2)) { next unless $seq1 eq $seq2; if (length($seq1) > $best_len) { $longest = $seq1; $best_len = length($seq1); } } } print $longest;
Note that there is an edge case when 2 or more common subsequences share the same length only the first will be found.
In reply to Re^2: True Brute Force Longest Common Sub Sequence
by tachyon-II
in thread True Brute Force Longest Common Sub Sequence
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |