题目:
分析:题目要求求出所有的回文字符串的个数,思考回文字符串的特点,有一个中心,并且两边字符相等,还有一个特点,回文字符串的长度可能是奇数也可能是偶数
假设每个字符都是一个回文字符串的中心,向两边扩展看有多少个回文字符串
代码:
class Solution {
int count = 0;
public int countSubstrings(String s) {
if(s.length() == 0){
return 0;
}
for(int i = 0; i < s.length(); i++){
//长度是奇数,因start=end
isReverse(s, i, i);
//长度是偶数,因end=start+1
isReverse(s, i, i+1);
}
return count;
}
void isReverse(String str, int start, int end){
while(start>=0 && end < str.length() && str.charAt(start) == str.charAt(end)){
start--;
end++;
count++;
}
}
}