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.1
2
3
4
5
6
7
8
9
10
11
12Example 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".
DP1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33class Solution {
public int countSubstrings(String s) {
int n = s.length();
if(n == 0)
return 0;
if(n == 1)
return 1;
boolean[][] isP = new boolean[n][n];
for(int i=0; i<n; i++)
isP[i][i] = true;
for(int i=0; i<n-1; i++)
isP[i][i+1] = s.charAt(i) == s.charAt(i+1);
int len = 3;
while(len <= n)
{
for(int i=0; i<=n-len; i++)
{
isP[i][i+len-1] = isP[i+1][i+len-2] && s.charAt(i) == s.charAt(i+len-1);
}
len++;
}
int count = 0;
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
if(isP[i][j]) count++;
return count;
}
}