Skip to content

Commit 38ba0af

Browse files
Create manchar_algorithm.md
1 parent fc5d6fd commit 38ba0af

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Manachar's Algorithm
2+
3+
Manacher's algorithm is a very handy algorithm with a short implementation that
4+
can make many programming tasks, such as finding the number of palindromic substrings
5+
or finding the longest palindromic substring, very easy and efficient. The running
6+
time of Manacher's algorithm is *O(N)* where *N* is the length of the input string.
7+
8+
## Implementation
9+
10+
Let:
11+
12+
1. s be a string of N characters
13+
14+
2. s2 be a derived string of s, comprising N * 2 + 1 elements, with each element
15+
corresponding to one of the following: the N characters in s, the N-1 boundaries
16+
among characters, and the boundaries before and after the first and last character
17+
respectively
18+
19+
3. A boundary in s2 is equal to any other boundary in s2 with respect to element
20+
matching in palindromic length determination
21+
22+
4. p be an array of palindromic span for each element in s2, from center to either
23+
outermost element, where each boundary is counted towards the length of a palindrome
24+
(e.g. a palindrome that is three elements long has a palindromic span of 1)
25+
26+
5. c be the position of the center of the palindrome currently known to include a
27+
boundary closest to the right end of s2 (i.e., the length of the palindrome = p[c]*2+1)
28+
29+
6. r be the position of the right-most boundary of this palindrome (i.e., r = c + p[c])
30+
31+
7. i be the position of an element (i.e., a character or boundary) in s2 whose palindromic
32+
span is being determined, with i always to the right of c
33+
34+
8. i2 be the mirrored position of i around c (e.g., {i, i2} = {6, 4}, {7, 3}, {8, 2},… when c = 5 (i.e., i2 = c * 2 - i)

0 commit comments

Comments
 (0)