Given a string S, find the longest palindromic substring in s. The maximum length of S is assume, and there exists one unique longest palindromic substring.
The longest palindrome string.
There are two ways of thinking:
1, from left to right to find the symmetry point, from the symmetry point (or two identical adjacent characters) to the side of the search, note the maximum length of the search.
2, set a two-dimensional bool array, a[i, j] = TRUE to indicate that the string from I to J is a palindrome string.
So first of all a[i, I] set to true (that is, the length of 1, is a palindrome), and then linearly look for the same character (2-length palindrome), if there is a a[i, i + 1] set to true.
Starting from the length of 3, judge the tail, if the same and a[i+1, j-1] = = TRUE (that is, the rest is a palindrome), then this substring is a palindrome string.
I used the second method. The code is as follows.
BOOLtab[ +][ +]; stringLongestpalindrome (strings) {stringMax; intn =s.size (); if(n = =0|| n = =1) returns; for(inti =0; I < n; i++) Tab[i][i]=true; for(inti =0; I < n-1; i++) { if(S[i] = = S[i +1]) {max= S.substr (I,2); Tab[i][i+1] =true; } } for(intK =3; K <= N; k++) { for(inti =0; I < N-k +1; i++) { intj = i + K-1; if(Tab[i +1][j-1] && s[i] = =S[j]) {Tab[i][j]=true; if(k >max.size ()) Max=S.substr (i, k); } } } returnMax; }
Two methods if I'm not mistaken, it should all be squared-level complexity.
Do not paste the running time, because the same code submitted two times a lot of time difference, can not explain the problem. But the idea is worth keeping track of.
Leetcode No.5 longest palindromic Substring