Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Input: "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Note:
- The input string length won't exceed 1000.
题意:给出一个字符串,找出它一共有多少个是回文数的子字符串,(子字符串相同但起始坐标不同的当成两个子字符串)。
思路:遍历字符串个每个字符,以字符本身为对称轴,向其左右两边一直扩散,直到两边不再是回文数;
同时以遍历的字符与右边紧邻的字符为对称轴,向其左右两边一直扩散,直到两边不再是回文数,如图所示:
代码:
class Solution {
int count =0;
public int countSubstrings(String s) {
int len = s.length();
for(int i=0;i<len;i++){
getPalindromic(s,i,i); //当前字符为对称轴
getPalindromic(s,i,i+1); //以两个字符为对称轴
}
return count;
}
public void getPalindromic(String str, int left, int right){
while(left >= 0 && right < str.length() && str.charAt(left) == str.charAt(right)){
left--;
right++;
count++;
}
}
}