思路:动态规划
class Solution {
public:
int countSubstrings(string s) {
vector<vector<bool>> dp(s.size(), vector<bool> (s.size(), 0));
int res = 0;
for (int i = s.size() - 1; i >= 0; i--){
for (int j = i; j < s.size(); j++){
if (s[i] == s[j]){
if (j - i <= 1) {
dp[i][j] = true;
res++;
}
else if (dp[i + 1][j - 1]){
dp[i][j] = true;
res++;
}
}
cout << dp[i][j] << endl;
}
}
return res;
}
};
双指针:
class Solution {
public:
int countSubstrings(string s) {
int res = 0;
for (int i = 0; i < s.size(); i++){
res += isSub(i, i, s.size(), s);
res += isSub(i, i + 1, s.size(), s);
}
return res;
}
int isSub(int i, int j, int end, string& s){
int res_tmp = 0;
while (i >= 0 && j < end){
if (s[i] == s[j]){
res_tmp++;
i--;
j++;
}
else break;
}
return res_tmp;
}
};
文章链接:代码随想录
题目链接:516.最长回文子序列
思路:dp[i + 1][j - 1] + 2 这里注意相等长度是加2
class Solution {
public:
int longestPalindromeSubseq(string s) {
vector<vector<int>> dp(s.size(), vector<int>(s.size()));
for (int i = 0; i < s.size(); i++) dp[i][i] = 1;
for(int i = s.size() - 2; i >= 0; i--){
for(int j = i + 1; j < s.size(); 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][s.size() - 1];
}
};
第五十七天打卡,今天就能把webserver项目视频学完了,加油!!!