- descrption
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".
- 解题思路
这道题是求一个字符串的回文子串的个数,回文字符串即正着读倒着读是一样的,如果将回文字符串从中间分开,那么从中间向左右两边的字符按顺序是相同的。可以根据这个属性来解决这个问题,我们将给定的字符串的每一个字符作为回文字符串的中间字符,遍历这个字符串即可得到回文子串的个数。当然,回文子串的长度有偶数个也有奇数个,分为两种情况:
假定第i个字符为回文子串正中间的字符:
如果回文子串长度为奇数,则长度为2i
对于j=0开始,在i-j >= 0, i+j<字符串总长的情况下
如果s[i-j] == s[i+j],则s[i-j]到s[i+j]是一个回文字串;
如果回文子串长度为偶数,则长度为2*i+2
对于j=0开始,在i-j-1 >= 0, i+j<字符串总长的情况下
如果s[i-j-1] == s[i+j],则s[i-j-1]到s[i+j]是一个回文字串;
- 代码如下
class Solution {
public:
int countSubstrings(string s) {
int len = s.size();
int ans = 0;
for(int i = 0 ; i < len; i++){
//i is in the middle of the substring
for(int j = 0; i-j >= 0 && i+j < len; j++){
if(s[i-j] == s[i+j]){
ans++;
}
else{
break;
}
}
for(int j = 0; i-1-j >=0 && i+j <len; j++){
if(s[i-1-j] == s[i+j]){
ans++;
}
else break;
}
}
return ans;
}
};
如有错误请指出,谢谢!