Topic:Given A stringS, find the longest palindromic substring inS. Assume that maximum length ofSis, and there exists one unique longest palindromic substring.
idea: The title requires a longest palindrome substring of S. The brute force solution is to enumerate all the substrings and then make a palindrome judgment on each substring. For pruning, we consider the use of dynamic programming to avoid repetitive judgments.
- DP[I][J] Indicates whether S[I...J] is a palindrome.
- Initialize: Dp[i][i] = True (0 <= i <= n-1); Dp[i][i-1] = True (1 <= i <= n-1); The rest is initialized to false
- According to the rules of palindrome, determine whether S[I...J] is a palindrome, if it is, need s[i] = = S[j] and dp[i+1][j-1] = = True.
- that is, the recursive formula: Dp[i][j] = (s[i] = = S[j] && dp[i+1][j-1] = = True)
Attention:
1. Other values are initialized to false, using memset to initialize all values initially false.
DP[I][J] Indicates whether the substring S[I...J] is a palindrome bool Dp[len][len]; memset (DP, 0, sizeof (DP));
2. Initialize Dp[i][i] and dp[i][i-1] are required for initialization. The second one is easy to forget, but it will be used later.
Dp[0][0] = true; for (int i = 1; i < Len; i++) { Dp[i][i] = true; Dp[i][i-1] = true; Easy to forget initialization, k = 2 o'clock, dp[i+1][i+k-2] to use }
3. The title requires the longest palindrome string to be returned, so we have to maintain two variables, one is the starting point of the longest palindrome and its length.
if (Longlen < k) { retleft = i; Longlen = k; }
4. In order to be exhaustive, we loop through all of the substring lengths, and the inner loop enumerates all the starting positions of the string.
for (int k = 2; k <= len; k++) //enumeration substring length {for (int i = 0; I <= len-k; i++) //enumeration substring starting position
Complexity: O (n^2)
AC Code:
Class Solution {Public:string Longestpalindrome (string s) {if (S.size () <= 1) return s; const int len = S.size (); DP[I][J] Indicates whether the substring S[I...J] is a palindrome bool Dp[len][len]; memset (DP, 0, sizeof (DP)); The beginning and length of the longest palindrome int retleft = 0; int longlen = 1; Dp[0][0] = true; for (int i = 1; i < Len; i++) {dp[i][i] = true; Dp[i][i-1] = true; Easy to forget initialization, k = 2 o'clock, dp[i+1][i+k-2] to use} for (int k = 2; k <= len; k++)//enumeration substring length { for (int i = 0; I <= len-k; i++)//enumeration substring start position {if (s[i] = = S[i+k-1] && dp[i+1 ][i+k-2]) {dp[i][i+k-1] = true; if (Longlen < k) {retleft = i; Longlen = k; }}}} return S.substr (Retleft, Longlen); }};
The problem also has an O (N) complexity solution: the longest continuous palindrome (longest palindromic Substring),longest palindromic Substring the longest palindrome string can be seen in these two blog posts.
[C + +] leetcode:99 longest palindromic Substring (longest palindrome string)