给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。
具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。
示例 1:
输入:"abc"
输出:3
解释:三个回文子串: "a", "b", "c"
示例 2:
输入:"aaa"
输出:6
解释:6个回文子串: "a", "a", "a", "aa", "aa", "aaa"
提示:
输入的字符串长度不会超过 1000 。
解法1:暴力,循环遍历出所有子串,然后判断子串是否是回文串。找出所有字串的时间复杂度是O(n^2),然后在用O(n)的时间来检查当前子串是不是回文串,所以时间复杂度是O(n^3).
class Solution {
int num ;
public int countSubstrings(String s) {
if(s == null || s.length() <=0) return 0;
char[] ch = s.toCharArray();
num = 0;
for(int i = 0;i<ch.length ;i++){
for(int j =i ;j<ch.length;j++){
if(isPalindrome(ch,i,j)) num++;
}
}
return num;
}
private boolean isPalindrome(char[] ch, int start, int end) {
if(end < start) return false;
if(start == end) return true;
while(start<end ) {
if(ch[start] == ch[end])
{start++;end--;}
else return false;
}
return true;
}
}
解法2:中心扩展法,枚举每一个可能的回文中心,然后用两个指针分别向左右两边拓展,当两个指针指向的元素相同的时候就拓展,否则停止拓展。枚举回文中心的是 的时间复杂度是O(n),对于每个回文中心拓展的次数也是O(n) 的,所以时间复杂度是 O(n^2)
class Solution {
int num ;
public int countSubstrings(String s) {
if(s == null || s.length() <=0) return 0;
char[] ch = s.toCharArray();
num = 0;
for(int i = 0;i<ch.length ;i++){
isPalindrome(ch,i,i);
isPalindrome(ch,i,i+1);
}
return num;
}
private void isPalindrome(char[] ch, int start, int end) {
//向两边扩展
while(start>=0 && end<ch.length && ch[start] == ch[end]) {
num++;
start--;
end++;
}
}
}