【
Given a string s, where to find the longest palindromic sequence. S may assume a maximum length of 1000.
Example 1:
Input:
"bbbab"
output:
4
a possible longest palindromic sequence is "bbbb".
Example 2:
Input:
"cbbd"
output:
2
a possible longest palindromic sequence is "bb".
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/longest-palindromic-subsequence
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
】
Dynamic programming, dp [i] [j] represents the longest sequence since i to j, i began to pay attention to here from the last element, then the recurrence formula is:
dp [i] [j] = MAX (dp [i + 1] [j], dp [i] [j-1]); dp [i] [j] = dp [i + 1] [j-1] + 2; return value dp [0] [len-1]
#defined MAX(a, b) (a) > (b) ? (a) : (b)
int longestPalindromeSubseq(char * s){
int len = strlen(s);
int i, j;
if (len == 0) return 0;
int dp[len][len];
memset(dp, 0, sizeof(int) * len * len);
for (i = len - 1; i >= 0; i--) {
dp[i][i] = 1;
for (j = i + 1; j < len; j++) {
if (s[i] == s[j]) {
dp[i][j] = dp[i+1][j-1] + 2;
} else {
dp[i][j] = MAX(dp[i+1][j], dp[i][j-1]);
}
}
}
return dp[0][len-1];
}