### comment on

 Need Help??

Hello good Monks. First let me start out with the problem: given an arbitrary list of strings, find the longest common substring. My approach to this problem is to grab one of the strings from the list, scan through it with successively decreasing substring lengths, and check the list for matches. This is simple, and seems quite effective, but I'm wondering if there are any problems with this approach? Could it be done simpler and more efficiently? Is there a well-known algorithm to do this, and I am too daft to find it?

Here is the working code I came up with. I do not have any particular problem with this code, I just wanted to run it by the Monastery to see if anyone could give me suggestions, or find any lurking problems:

```#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;

for ([ qw(fooabc123 fooabc321 foobca232) ],
[ qw(abcfoo123 bcafoo321 foo123abc) ],
[ qw(foo bor boz bzo) ]) {

print Dumper(\$_);
print findlcs(@{ \$_ }), "\n";
print "---\n";
}

sub findlcs {
my \$substr = \$_[0];
my \$len = length \$_[0];
my \$off = 0;

while (\$substr) {
my @matches = grep /\Q\$substr/, @_;
#printf "%s%-".(length(\$_[0])-\$off)."s matches %d\n",
#       " " x \$off, \$substr, scalar @matches;

last if @matches == @_;

\$off++;
\$len-- and \$off=0 if \$off+\$len > length \$_[0];

\$substr = substr \$_[0], \$off, \$len;
}

return \$substr;
}

In reply to finding longest common substring by revdiablo

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.
• Posts may use any of the Perl Monks Approved HTML tags:
a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, 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, 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: & & < < > > [ [ ] ]
• Link using PerlMonks shortcuts! What shortcuts can I use for linking?

Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (2)
As of 2020-11-30 04:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?

No recent polls found

Notices?