Блог пользователя 300iq

Автор 300iq, 7 лет назад, По-английски

You are given a string $$$s$$$, and for each $$$r$$$ you need to find the largest $$$L_r$$$, such that $$$s[r - L_r + 1 \ldots r]$$$ is a palindrome.

It is possible to solve this problem with the eertree or with Manacher's algorithm with some data structures, but I will describe a simpler way.

You will need some black box, that for any substring $$$s[l \ldots r]$$$ can check in $$$\mathcal{O}{(1)}$$$ if it is a palindrome. The easiest such black box is a polynomial hash, but also you can precalculate stuff from Manacher's algorithm and then check that $$$\frac{(l+r)}{2}$$$ is a middle of a long enough palindrome.

The key fact here is that $$$L_i \leq L_{i-1} + 2$$$, because if $$$s[l \ldots r]$$$ is a palindrome, then $$$s[l+1 \ldots r-1]$$$ is a palindrome too.

With this observation, we can use our black box to find the required values!

Let's assume that you already know $$$L_1, L_2, \ldots, L_{i-1}$$$ and we want to calculate $$$L_i$$$.

Starting from $$$L_i = L_{i-1}+2$$$, decrease $$$L_i$$$ while $$$s[i - L_i + 1 \ldots i]$$$ is not a palindrome.

The number of black box operations of this algorithm is $$$\sum{(L_{i-1} + 2 - L_i)}$$$ $$$\leq 2 n$$$.

  • Проголосовать: нравится
  • +324
  • Проголосовать: не нравится

»
7 лет назад, скрыть # |
 
Проголосовать: нравится +59 Проголосовать: не нравится

u r very cute : )

»
7 лет назад, скрыть # |
 
Проголосовать: нравится +251 Проголосовать: не нравится

This is the worst story I have ever heard.

»
7 лет назад, скрыть # |
 
Проголосовать: нравится +3 Проголосовать: не нравится

once upon a time. there is a man, named palindrome.

like my story/

»
7 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

just great

»
7 лет назад, скрыть # |
 
Проголосовать: нравится +25 Проголосовать: не нравится

better than Twilight

»
7 лет назад, скрыть # |
 
Проголосовать: нравится +59 Проголосовать: не нравится

Cool story bro.

»
7 лет назад, скрыть # |
 
Проголосовать: нравится +32 Проголосовать: не нравится
»
7 лет назад, скрыть # |
 
Проголосовать: нравится +56 Проголосовать: не нравится

Don't tell anybody, but I've heard that it's also possible to calculate the length of the longest border of each prefix of the string in a linear time :o

»
7 лет назад, скрыть # |
Rev. 2  
Проголосовать: нравится +69 Проголосовать: не нравится

And to further simplify this algorithm (that is, to make your "black box" built-in) you may store for each prefix the length of its second largest $$$L_r$$$ and also the position in which $$$s[r-L_r+1...r]$$$ occurs for the first time. In this way you may traverse suffix-palindromes of $$$s[1...i-1]$$$ only. Seems simple and resembles prefix-function, right? Yeah, except that it's exactly eertree.

»
7 лет назад, скрыть # |
 
Проголосовать: нравится +204 Проголосовать: не нравится