题目来源:
https://leetcode-cn.com/problems/palindromic-substrings/
题目描述:
解题思路:
从第一个字符开始向后遍历,当遍历到第i个字符时,还有将这个字符做为中心字符,去寻找以这个字符为中心的回文子串。假设这时下标i为5,那么需要判断下标为5,456,34567,2345678等等这些字符串是否为回文子串。除此之外还要寻找以i和i的下一个字符为中心的回文子串。假设这时下标i为5,那么需要判断下标为56,4567,345678等等这些字符串是否为回文子串。将这些是回文子串的字符串个数统计起来就可以了。
代码如下:
class Solution {
public int countSubstrings(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int count = 0;
char[] arr = s.toCharArray();
for (int i = 0; i < s.length(); i++) {
count += countSubstrings(arr, i, i);
count += countSubstrings(arr, i, i + 1);
}
return count;
}
private int countSubstrings(char[] arr, int left, int right) {
int count = 0;
while (left >= 0 && right < arr.length && arr[left] == arr[right]) {
count++;
left--;
right++;
}
return count;
}
}