647. 回文子串
class Solution {
public:
int countSubstrings(string s) {
vector<bool> dp(s.size(), false);
int res =0;
for(int i=0; i<s.size(); i++)
{
for(int j=0; j<=i; j++){
if(s[i]==s[j]){
if(i-j<=1) dp[j] = true;
else dp[j] = dp[j+1];
}
else dp[j] = false;
if(dp[j]) res++;
}
}
return res;
}
};
class Solution {
public:
int extend(string& s, int i, int j){
int res=0;
while(i>=0 && j<s.size() && s[i]==s[j]){
i--;
j++;
res++;
}
return res;
}
int countSubstrings(string s) {
int result=0;
for(int i=0;i<s.size(); i++){
result += extend(s,i,i);
result += extend(s,i,i+1);
}
return result;
}
};
516.最长回文子序列
class Solution {
public:
int longestPalindromeSubseq(string s) {
vector<int> dp(s.size(), 0);
int pre =0, cur =0;
for(int i=0; i<s.size(); i++)
{
for(int j=i; j>=0; j--)
{
cur = dp[j];
if(s[j]==s[i]){
if(i-j<=1) dp[j] = i-j+1;
else dp[j] = pre + 2;
}
else dp[j] = max(dp[j+1], dp[j]);
pre = cur;
}
}
return dp[0];
}
};