给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。
具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。
示例 1:
输入:"abc"
输出:3
解释:三个回文子串: "a", "b", "c"
示例 2:
输入:"aaa"
输出:6
解释:6个回文子串: "a", "a", "a", "aa", "aa", "aaa"
方法1:中心扩张法
class Solution {
public int countSubstrings(String s) {
int n = s.length();
int res = 0;
boolean[][] dp = new boolean[n][n];
for(int i=0;i<n;++i){
for(int j=0;j<=i;++j)
if(s.charAt(i) == s.charAt(j)&&(i-j<2 || dp[j+1][i-1])){
dp[j][i] = true;
++res;
}
}
return res;
}
}
时间复杂度:O(n^2)
空间复杂度:O(n^2)
方法2:动态规划
class Solution {
public int countSubstrings(String s) {
int n = s.length();
int res = 0;
for(int i=0;i<n;++i){
res = midextend(s,i,i,res,n);
res = midextend(s,i,i+1,res,n);
}
return res;
}
public int midextend(String s,int i,int j,int res,int n){
while(i >= 0 && j < n && s.charAt(i) == s.charAt(j)){
--i;
++j;
++res;
}
return res;
}
}
时间复杂度:O(n^2)
空间复杂度:O(1)