647. 回文子串
题目链接:力扣
代码:
class Solution {
public:
int countSubstrings(string s) {
int n = s.size();
vector<vector<bool>> dp(n,vector<bool> (n,false));
int result = 0;
for(int i = n-1; i >= 0; i--)
{
for(int j = i ; j < n; j++)
{
if(s[i] == s[j])
{
if(j-i <= 1)
{
result++;
dp[i][j] = true;
}else if(dp[i+1][j-1])
{
result++;
dp[i][j] = true;
}
}
}
}
return result;
}
};
代码(双指针法):
class Solution {
public:
int extent(string s, int i , int j ,int n)
{
int res = 0;
while(i >= 0 && j < n && s[i] == s[j])
{
res++;
j++;
i--;
}
return res;
}
int countSubstrings(string s) {
int n = s.size();
int result = 0;
for(int i = 0 ; i < n; i++)
{
result += extent(s,i,i,n);
result += extent(s,i,i+1,n);
}
return result;
}
};
516.最长回文子序列
题目链接:力扣
代码:
class Solution {
public:
int longestPalindromeSubseq(string s) {
int n = s.size();
int result = 0;
vector<vector<int>> dp(n,vector<int>(n,0));
for(int i = 0 ; i < n ; i++)
dp[i][i] = 1;
//dp[i][j]:字符串s在[i, j]范围内最长的回文子序列的长度为dp[i][j]
for(int i = n-1; i >= 0; i--)
{
for(int j = i+1; j < n ; 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][n - 1];
}
};
动态规划总结篇
题目链接:代码随想录