I throw my hat into the ring with my recursive implementation. I think it could perform reasonably well, since it is a divide-and-conquer type solution.
I'm not sure how it will stand up to the hash-based solutions, and there might be some "correctness" issues...
For the bonus, though, mine increments the count for *any* length of matching substrings.
There are probably many opportunities for optimizations here... please offer criticism.
#! perl -w
use strict;
my $hits = 0;
sub common_substr {
my($s1, $s2) = @_;
print qq(s1 = $s1, s2 = $s2\n);
($s1, $s2) = ($s2, $s1) if length($s2) < length($s1);
if ($s1 eq $s2) {
$hits++;
return if length($s1) == 1;
}
my %hash = map { $_ => 1 } split(//, $s1);
my $arr = [];
for my $s (split(//, $s2)) {
push(@$arr, $s) if ! exists($hash{$s});
}
my $splitters = join('|', @$arr);
for my $s (split(/$splitters/, $s2)) {
common_substr($s, $s1);
}
}
common_substr("abcef", "abcdef");
print "hits = $hits\n";
Where do you want *them* to go today?
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.