Manacher algorithm - the longest palindromic substring

   / * When evaluated longest palindromic substring, if the enumeration endpoint about violence, resulting in the exponential complexity. Optimization point, a two-dimensional array to DP, the complexity can be reduced to O (m * n) m, n is the length of the two strings. In this paper, Manacher algorithms are better than the two-dimensional DP time or space. * / 


. 1
#include <the iostream> 2 #include < String > . 3 #define Maxsize 100 . 4 the using namespace STD; . 5 int Len [Maxsize]; . 6 int main () { . 7 String pre; . 8 CIN >> pre; . 9 String Tool = " { " ; // prevent cross-border. 10 int len = ( int ) pre.length (); 11 for(int i = 0; i < len; i++){ 12 tool+="#"; 13 tool+=pre[i]; 14 } 15 tool+="#"; 16 tool+="}"; // 防止越界 17 int mx = 0,ans = 0,po = 0; 18 int len2 = (int)tool.length(); 19 for(int I = . 1 ; I <LEN2; I ++ ) { 20 is / * select the lower bound * / 21 is IF (MX> I) 22 is Len [I] = min (MX-I, Len [ 2 * weight PO- I]); 23 is the else 24 Len [I] = . 1 ; 25 / * upper bound Analyzing * / 26 / * Note that in either case, the algorithm can not guarantee that the newly calculated palindromic sequence length less than a certain upper bound, only possible to draw 27 its lower bound. The main part of the algorithm is simplified to avoid the repeated determination of the lower bound. For certain palindromic substring may be 28 to be longer unknown, and therefore must be additionally determined. * / 29 the while (Tool [I-Len [I]] == Tool [I +Len [I]]) 30 len [I] ++ ; 31 is / * is determined whether to update the rightmost end palindromic sequence, the answer * / 32 IF (len [I] + I> MX) { 33 is MX = len [I ] + I; 34 is PO = I; 35 } 36 ANS = max (ANS, Len [I]); 37 [ } 38 is COUT ans- << . 1 ; 39 return 0 ; 40 }

Manacher algorithm, the complexity of O (n) determines the maximum length of the palindrome substring.

Specific principles and certification process, please refer to the following two blog:

https://segmentfault.com/a/1190000003914228

https://www.cnblogs.com/z360/p/6375514.html

Guess you like

Origin www.cnblogs.com/popodynasty/p/12122229.html
Recommended