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.
思路
从中心向左右扩展,核心是确定中心center,对于奇偶长度的字符串都是一个道理
先确定字符串里哪一个字符作为你的中心,确定之后,就向左右扩展一个单位,然后判断你的左右位置是否越界,因为位置不可能为负数,也不可能大于你的字符串长度,再判断你的左右字符是否相等,若相等就count++,左右继续移动,若不相等就换中心点。
偶数的话最初就把你的left和right设为两个相邻值,判断条件一样。
class Solution {
int count = 0;
public int countSubstrings(String s) {
if(s==null|s.length()==0)
return 0;
for (int i = 0; i < s.length(); i++) {
kuozhan(s,i,i);
kuozhan(s, i, i+1);
}
return count;
}
void kuozhan(String s,int left, int right) {
while(left>=0&&right<s.length()&&s.charAt(left)==s.charAt(right)) {
count++;
left--;
right++;
}
}