Given a string, your task is to count how many palindromic substrings
in this string.The substrings with different start indexes or end indexes are counted
as different substrings even they consist of same characters.Example 1:
Input: “abc” Output: 3 Explanation: Three palindromic strings: “a”,
“b”, “c”.Example 2:
Input: “aaa” Output: 6 Explanation: Six palindromic strings: “a”, “a”,
“a”, “aa”, “aa”, “aaa”.Note:
The input string length won’t exceed 1000.
动态规划,16ms
class Solution {
public:
int countSubstrings(string s) {
int len = s.size();
if (len <= 1) {
return len;
}
vector<vector<int> > dp(len , vector<int>(len,0));
int res = 0;
for (int i = 0; i < len; ++i) {
dp[i][i] = 1;
res += dp[i][i];
//cout << dp[i][i] << endl;
if (i+1<len&&s[i] == s[i + 1]) {
dp[i][i + 1] = 1;
res += dp[i][i+1];
//cout << dp[i][i+1] << endl;
}
}
int i, j;
for (j = 2; j <len; ++j) {
for (i = 0; i+j < len; ++i) {
if (s[i] == s[i+j]) {
dp[i][i+j] = dp[i + 1][i+j - 1];
res += dp[i][i+j];
}
}
}
return res;
}
};