1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
public int countSubstrings(String s) {
if(s==null||s.length()==0){
return 0;
}
int ans = 0;
for(int i=0;i<s.length();i++){
// 1. 以i为中心(奇数长度回文)
ans += countPalindrome(s, i, i);
// 2. 以i和i+1为中心(偶数长度回文)
ans += countPalindrome(s, i, i+1);
}
return ans;
}
private int countPalindrome(String s,int left,int right) {
int count = 0;
while(left>=0&& right< s.length()&&s.charAt(left)==s.charAt(right)){
count++;
left--;
right++;
}
return count;
}
|