sub f { @a = split //, shift; $ih = shift; for $i (0 .. $#a){ $e = $a[$i]; ${$ih}{$e} = 1; for $y ($i+1 .. $#a){ $e .= $a[$y]; ${$ih}{$e} = 1; } } } ($l, $m) = split /\s/, ; $_ = ; chomp; %h = (); f($_, \%h); while(){ chomp; %th = (); f($_, \%th); $h{$_}++ foreach (keys %th); } foreach $key (keys %h){ if($h{$key} == $m){ $r[length($key)] = [] if ! exists $r[length($key)]; push $r[length($key)], $key; } } print "@{$r[$#r]}\n"; __DATA__ 3 2 ac bc b