题目:给定一个字符串,请问该字符串中有多少个回文连续子 字符串?例如,字符串"abc"有3个回文子字符串,分别 为"a"、“b"和"c”;而字符串"aaa"有6个回文子字符串,分别为"a"、“a”、“a”、“aa”、“aa"和"aaa”。
题目分析
通过双指针法从中间分别向两边同时移动,因为字符串长度可能为奇数也可能为偶数,为奇数时中心点只有一个,而为偶数时中心点则有两个所以当字符串长度为奇数时两个指针的起点都在哪一个中心点上而为偶数时则分别在两个中心点上。
具体实现
public int countSubstrings(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int count = 0;
for (int i = 0; i < s.length(); i++) {
// 字符串长度为奇数的情况
count += countPalindrome(s, i, i);
// 字符串长度为偶数的情况
count += countPalindrome(s, i, i + 1);
}
return count;
}
// 记录从中心点分别向两边移动指针的过程中的回文个数
public int countPalindrome(String s, int start, int end) {
int count = 0;
// 当两个指针没有越界,并且两个指针指向的字符相同时进入循环
while (start >= 0 && end < s.length()
&& s.charAt(start) == s.charAt(end)) {
count++;
start--;
end++;
}
return count;
}