【動態規劃 迴文串13】LeetCode 647. Palindromic Substrings
阿新 • • 發佈:2019-01-02
LeetCode 647. Palindromic Substrings
Solution1:我的答案
動態規劃,易解
class Solution {
public:
int countSubstrings(string s) {
int n = s.size();
if (n == 0) return 0;
else if (n == 1) return 1;
int dp[n][n] = {0}, res = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
dp[j][i] = (s[j] == s[i]) && (i - j < 2 || dp[j+1][i-1]);
if (dp[j][i]) res++;
}
}
return res;
}
};