LeetCode ---- longest palindromic substring

topic

Title Description

Given a string  s, to find  s the longest substring palindromic. You may assume that  s the maximum length of 1000.

Examples

Enter: "babad"
Output: "bab"
Note: "aba" is a valid answer.

analysis

  Violence: Direct from beginning to end next iteration of both sides to find the longest substring can be extended through the center.

  Horse-drawn vehicles algorithm (Manacher): Use Manacher algorithm, dynamic programming to find the longest palindrome substring

Diagram

  Construction. . .

Code

 1     string longestPalindrome(string s) {
 2         int len = s.length();
 3         string ma = "#";
 4         for(int i = 0; i < len; ++i) {
 5             ma.push_back(s[i]);
 6             ma.push_back('#');
 7         }
 8         int mx = 0, id = 0, new_len = len*2+1, p = 0, mp[new_len];
 9         for(int i = 0; i < new_len; ++i) {
10             mp[i] = mx > i ? min(mp[2*id-i], mx-i) : 1;
11             while(i-mp[i] >= 0 && ma[i-mp[i]] == ma[i+mp[i]]){
12                 // char x = ma[i+mp[i]], y = ma[i-mp[i]];
13                 ++mp[i];
14             }
15             if(i+mp[i] > mx) {
16                 mx = i + mp[i];
17                 id = i;
18             }
19             if(mp[i] > mp[p]) p = i;
20         }
21         len = mp[p] - 1;
22         p = p/2 - len/2;
23         return s.substr(p, len);
24     }

 

Guess you like

Origin www.cnblogs.com/qq188380780/p/11305419.html