Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000.
Example 1:
- Input: "bbbab"
- Output: 4
- One possible longest palindromic subsequence is "bbbb".
Example 2:
- Input: "cbbd"
- Output: 2
- One possible longest palindromic subsequence is "bb".
C Solution:
int longestPalindromeSubseq(char* s) {
int len = strlen(s);
if (len == 1) return 1;
int *bottom = malloc(len * sizeof(int));
int *top = malloc(len * sizeof(int));
int i, j;
for (i = 0; i < len; i++) bottom[i] = 1;
for (i = 1; i < len; i++) {
if (s[i] == s[i - 1]) top[i] = 2;
else top[i] = 1;
}
for (i = 2; i < len; i++) {
int *higher = bottom;
for (j = len - 1; j >= i; j--) {
if (s[j] == s[j - i]) higher[j] = 2 + bottom[j - 1];
else higher[j] = top[j - 1] > top[j] ? top[j - 1] : top[j];
}
bottom = top;
top = higher;
}
len = top[len - 1];
free(bottom);
free(top);
return len;
}
Summary:
- Nice.
LeetCode: 516. Longest Palindromic Subsequence





近期评论