Longest palindromic sequence
Topic Link https://leetcode.com/problems/longest-palindromic-subsequence/
Given a string s, where to find the longest palindromic sequence. S may assume a maximum length of 1000.
The difference between the longest and the palindromic sequence palindromic a question longest substring that is a substring of a string in a continuous sequence, and the sequence is a string of characters maintain the relative position of the sequence, e.g., "bbbb" can string "bbbab" but not a sub-sequence substring.
动态规划: dp[i][j] = dp[i+1][j-1] + 2 if s.charAt(i) == s.charAt(j) otherwise, dp[i][j] = Math.max(dp[i+1][j], dp[i][j-1])
class Solution {
public:
int longestPalindromeSubseq(string s) {
int len = s.size();
if(len <= 1)
return len;
int dp[len+1][len+1] = {0};
memset(dp, 0, sizeof(dp));
for(int i=len-1; i>=0; i--) {
dp[i][i] = 1;
for(int 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];
}
};
A palindromic sequence number of strings
Topic links: https://leetcode.com/problems/palindromic-substrings/
Given a string, your task is to calculate how many string palindrome substring.
Substring having a different start position or the end position, even by the same characters will be counted as a different string.
class Solution {
public:
int countSubstrings(string s) {
int len = s.size();
if(len <= 1)
return len;
int res = 0;
for(int i=0; i<len; i++) {
check(s, i, i, res);
check(s, i, i+1, res);
}
return res;
}
void check(string s, int i, int j, int &res) {
while(true) {
if(i>=0 && j < s.size() && s[i] == s[j]) {
res ++;
i--, j++;
} else
break;
}
return ;
}
};