题目:
![](https://img-blog.csdnimg.cn/direct/7ff7dc9ae24445a1843f80a4985cda6f.png)
代码(首刷看解析 2024年2月29日):
class Solution {
public:
bool check(string s, int i, int j) {
if (i == j) return true;
while (i < j) {
if (s[i] != s[j]) return false;
++i;
--j;
}
return true;
}
// 动态规划
int countSubstrings(string s) {
// 定义dp dp[i][j] 代表s[i:j]是否是回文串
int n = s.size();
vector<vector<bool>> dp(n, vector<bool>(n, false));
// 遍历顺序 i n->0 j 0->n
int res = 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) {
res++;
dp[i][j] = true;
} else if (dp[i + 1][j - 1]) {
res++;
dp[i][j] = true;
}
}
}
}
return res;
}
};