寻找字符串中满足回文字符串的连续子字符串的数目(见注释):
class Solution {
public:
int countSubstrings(string s) {
if(s.size()==0)
return 0;
int len = s.size();
bool table[len][len]={0}; //表示i与j之间是否为回文字符串
int res = len;//初始化为长度为1的回文字符串数目
for(int i=0;i<s.size()-1;i++)
{
table[i][i]=1;
if(s[i]==s[i+1])
{
res++; //加上长度为2的回文字符串数目
table[i][i+1]=1;
}
}
table[len-1][len-1]=1; //init the table
for(int lenth = 3 ; lenth <= len;lenth++) //长度为3--lenth的回文字符串
{
for(int i =0;i< len-lenth+1;i++)
{
int j=i+lenth-1;
if(s[i]==s[j]&&table[i+1][j-1]) //i--j之间是否为回文字符串
{
res++;
table[i][j]=1;
}
}
}
return res;
}
};