647. 回文子串
给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。
具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。
示例 1:
输入:"abc"
输出:3
解释:三个回文子串: "a", "b", "c"
示例 2:
输入:"aaa"
输出:6
解释:6个回文子串: "a", "a", "a", "aa", "aa", "aaa"
提示:
- 输入的字符串长度不会超过 1000 。
中心拓展法:
这里对于回文串长度为奇数和偶数是分开来处理的,对于奇数,中心点是一个数,start=end,对于偶数中心点是两个数,因为是从左往右遍历的所以中心点是 end = start +1
class Solution {
int num = 0;
public int countSubstrings(String s) {
for(int i = 0; i< s.length(); i++){
//处理奇串
count(s,i,i);
//处理偶串
count(s,i,i+1);
}
return num;
}
public void count(String s , int start, int end){
//判断是否相同
while(start >=0 && end<s.length() && s.charAt(start) == s.charAt(end)){
num++;
//从中心向外扩展,之后再判断是否相同
start --;
end ++;
}
}
}