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".
Note:
- The input string length won't exceed 1000.
代码1:
class Solution {
public:
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;
}
};
代码2:
class Solution {
public:
int countSubstrings(string s) {
int midpos=0,len=0,res=0,size=s.size();
for(;midpos<size;midpos++){
while(midpos-len>=0 && midpos+len<size){
if(s[midpos-len]==s[midpos+len]){
res++;
len++;
}
else{ break; }
}
len=0;
while(midpos-len-1>=0 && midpos+len<size){
if(s[midpos-len-1]==s[midpos+len]){
res++;
len++;
}
else{ break; }
}
len=0;
}
return res;
}
};
代码3(动态规划?):