summaryrefslogblamecommitdiffstats
path: root/KMP.pl
blob: 7c80d82d4e16418f1b2a7248982e7a70b7843d26 (plain) (tree)
























                                                               
#!/usr/bin/env perl
use strict;
use warnings;
use 5.016;

chomp(my $str = <>);

my @failure = (0);

my $idx = 0;
for my $start (1..(length($str) - 1)) {
    while (1) {
        if (substr($str, $start, 1) eq substr($str, $idx, 1)) {
            ++$idx;
            last;
        }
        else {
            last if $idx == 0;
            $idx = $failure[$idx - 1];
        }
    }
    push @failure, $idx;
}

say join(' ', @failure);