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.
分析
dp[i][j] 如果等于1就表示 string s 从下标i到j的那部分是 palindromic 的,而 string s 从 m 到 n 的部分只需要满足 s[m]==s[n] 并且 dp[m+1][n-1]==1 (即首尾相等,并且中间的是 palindromic )就是palindromic.
class Solution{
private:
int dp[1000][1000];
public:
int countSubstrings(string s) {
for(int i=0;i<s.size();i++)
dp[i][i]=1;
int cnt=s.size();
for(int len=2;len<=s.size();len++)
for(int i=0;i<=s.size()-len;i++)
if(len==2&&s[i]==s[i+1]){
dp[i][i+1]=1;
cnt++;
}else if(s[i]==s[i+len-1]&&dp[i+1][i+len-2]==1){
dp[i][i+len-1]=1;
cnt++;
}
return cnt;
}
};