Skip to content

Instantly share code, notes, and snippets.

@xpqz
Last active February 5, 2022 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xpqz/c19ca3ef97b5437761cad3925ba5388c to your computer and use it in GitHub Desktop.
Save xpqz/c19ca3ef97b5437761cad3925ba5388c to your computer and use it in GitHub Desktop.
Manacher's algorithm for finding the longest palindromic substring in Dyalog APL (⎕IO←0)
∇ res←manacher str;S;c;r;radii;i;ir
c r radii←0 0 (0↑⍨≢S←'|',∊'|',⍨⍪str)
:for i :in ⍳≢S
radii[i]←{r>i:radii[(2×c)-i]⌊r-i⋄0}⍬
:trap 3 ⍝ Catch index errors if the below goes out of bounds
:while =/S[i(+,-)1+i⊃radii]
radii[i]+←1
:endwhile
:endtrap
:if r<ir←i+i⊃radii
c r←i ir
:endif
:endfor
c←radii⍳r←⌈/radii
res←S[c(+(⊢+∘⍳1+-)-)r]~'|'
@xpqz
Copy link
Author

xpqz commented Feb 4, 2022

Passable tradfn implementation of Manacher's algorithm (https://en.wikipedia.org/wiki/Longest_palindromic_substring)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment