题目:
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.
思路:每个回文子串都可以看作是以第 i 个字母或者第 i-1 和第 i 个字母为轴的一个对称字符串。因此,中心思想是遍历每个“轴”,找出每个轴所对应的回文子串。
int countSubstrings(string s) {
int res = 0, n = s.length();
for(int i = 0; i < n; i++){
for(int j = 0; i-j >= 0 && i+j < n && s[i-j] == s[i+j]; j++)res++; //substring s[i-j, ..., i+j]
for(int j = 0; i-1-j >= 0 && i+j < n && s[i-1-j] == s[i+j]; j++)res++; //substring s[i-1-j, ..., i+j]
}
return res;
}