题目:
给定一个字符,求其有多少个回文子字符串。回文的定义是左右对称。
思路:
可以从字符串的每个位置开始,向左向右延长,判断存在多少以当前位置为中轴的回文
子字符串。
class Solution {
public int countSubstrings(String s) {
int n = s.length(),ans = 0;
for (int i = 0; i<2*n-1; ++i){
int l = i / 2, r = i / 2 + i % 2;
while (l >= 0 && r < n && s.charAt(l) == s.charAt(r)) {
--l;
++r;
++ans;
}
}
return ans;
}
}