Help language development. Donate to The Perl Foundation

Algorithm::Manacher cpan:TITSUKI last updated on 2018-04-01
[![Build Status](](


Algorithm::Manacher - a perl6 implementation of the extended Manacher's Algorithm for solving longest palindromic substring(i.e. palindrome) problem


    use Algorithm::Manacher;

    # "たけやぶやけた" is one of the most famous palindromes in Japan.
    # It means "The bamboo grove was destroyed by a fire." in English.
    my $manacher = => "たけやぶやけた");
    $; # True
    $manacher.find-longest-palindrome(); # {"たけやぶやけた" => [0]};
    $manacher.find-all-palindrome(); # {"た" => [0, 6], "け" => [1, 5], "や" => [2, 4], "たけやぶやけた" => [0]}


Algorithm::Manacher is a perl6 implementation of the extended Manacher's Algorithm for solving longest palindromic substring problem. A palindrome is a sequence which can be read same from left to right and right to left. In the original Manacher's paper [0], his algorithm has some limitations(e.g. couldn't handle a text of even length). Therefore this module employs the extended Manacher's Algorithm in [1], it enables to handle a text of both even and odd length, and compute all palindromes in a given text.


    my $manacher = => $text);


### find-all-palindrome => "たけやぶやけた").find-all-palindrome(); # {"た" => [0, 6], "け" => [1, 5], "や" => [2, 4], "たけやぶやけた" => [0]}

Finds all palindromes in a text and returns a hash containing key/value pairs, where key is a palindromic substring and value is an array of its starting positions. If there are multiple palindromes that share the same point of symmetry, it remains the longest one.

### is-palindrome => "たけやぶやけた").is-palindrome(); # True => "たけやぶやけたわ").is-palindrome(); # False => "Perl6").is-palindrome(); # False

Returns whether a given text is a palindrome or not.

### find-longest-palindrome => "たけやぶやけた").find-longest-palindrome(); # {"たけやぶやけた" => [0]}; => "たけやぶやけた。、だんしがしんだ").find-longest-palindrome(), {"たけやぶやけた" => [0], "だんしがしんだ" => [9]};

Returns the longest palindrome. If there are many candidates, it returns all of them.


titsuki <[email protected]>


Copyright 2016 titsuki

This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.

This algorithm is from

  * [0] Manacher, Glenn. "A New Linear-Time``On-Line''Algorithm for Finding the Smallest Initial Palindrome of a String." Journal of the ACM (JACM) 22.3 (1975): 346-351.

  * [1] Tomohiro, I., et al. "Counting and verifying maximal palindromes." String Processing and Information Retrieval. Springer Berlin Heidelberg, 2010.