[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [FWP] longest substring with unique characters



Casey R. Tweten wrote:
> my @lines = map { chomp; $_ } <DATA>;
> LINE: foreach ( @lines ) {
>   my @chars  = split //;
>   my $length = $#chars;
>   my $end    = $length;
>   while ( --$end ) {
>     my $start  = 0;
>     while ( $start + $end <= $length ) {
>       my $substr = join '', @chars[$start..$start+$end];
>       $substr =~ /(.).*(\1)/ ? $start++ : do {
>                                               print "$substr\n";
>                                               next LINE;
>                                              };
>     }
>   }
> }
> __DATA__
> that
> abcdefa
> abcdabc
> testing
> this test

Little bug here. Try it with the word "abcdefg" and you will se that it will
give you "abcdef", when the answer is "abcdefg" (at least, for me, a string
is substring of itself...). But it's easy to correct this bug. Where you
wrote
>   my $length = $#chars;
you should have written
>   my $length = @chars;

Another one: if you give it a one-letter word, it won't print anything. To
correct this, change
>   while ( --$end ) {
to
>   while ( $end-- ) {


I actually didn't understand what the test
>     while ( $start + $end <= $length ) {
is about, (Actually I haven't thought much about it...) but it appears to do
the right job, at least with the test words...

Branden


==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe