Common pattern in different strings? Using KMP?

I think I solved the corresponding problem on rosalind.info. Here is my solution:

#!/usr/bin/perl use strict; use warnings; sub kmp { my @T = (-1, 0); my ($pos, $cnd) = (2, 0); while ( $pos <= @_ ) { if ($_[$pos-1] eq $_[$cnd]) { $T[$pos++] = ++$cnd } elsif ($cnd > 0) { $cnd = $T[$cnd] // 0 } else { $T[$pos++] = 0 } } shift @T; return @T; } use List::Util qw(max min); sub lcs { my @first = split //, my $first = shift; my $n = @first; my @string = map [ split //, $_ ], @_; my ($pos, $length) = (0, 0); SUFFIX: for my $p ( 0 .. $n - 1 ) { shift @first if $p; my @max; for (@string) { my @kmp = kmp @first, '$', @$_; my $max = max @kmp; next SUFFIX if $max < $length; push @max, $max; } if ((my $min = min @max) > $length) { ($pos, $length) = ($p, $min); } } return substr $first, $pos, $length; } open my $f, '< rosalind_lcs.txt' or die "could not open: $!"; say lcs <$f>;

Hope this will help


In reply to Re: Pattern Searching by grondilu
in thread Pattern Searching by aseee

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.