# lc.647 回文子串+扩展

2022-05-17 11:31:56  阅读：42  来源： 互联网

1.dp法

``````class Solution {
public:
int countSubstrings(string s) {
int count = 0;
vector<vector<bool>> dp(s.size(), vector<bool>(s.size(), false));
for(int i = s.size()-1; i >= 0; i--)
{
for(int j = i; j < s.size(); j++)
{
if(s[i] == s[j] && (j - i <= 1 || dp[i+1][j-1]))
{
count++;
dp[i][j] = true;
}
}
}
return count;
}
};
``````

2.中心扩散法

``````class Solution {
public:
int countSubstrings(string s) {
int res = 0;
for(int i = 0; i < s.size(); i++)
{
res += extend(s, i, i);
res += extend(s, i, i+1);
}
return res;
}

int extend(const string s, int l, int r)
{
int count = 0;
while(l >= 0 && r < s.size() && s[l] == s[r])
{
count++;
l--, r++;
}
return count;
}
};
``````

3.中心扩散并输出

``````class Solution {
public:

string str;
int countSubstrings(string s) {
vector<string> ans;
int res = 0;
for(int i = 0; i < s.size(); i++)
{
str.clear();
res += extend(s, i, i, str, ans);
str.clear();
res += extend(s, i, i+1, str, ans);
}
for(auto i : ans)
cout << i << ' ';
return res;
}

int extend(const string s, int l, int r, string &str, vector<string>& ans)
{
int count = 0;
while(l >= 0 && r < s.size() && s[l] == s[r])
{
str = s.substr(l, r-l+1);
ans.push_back(str);
count++;
l--, r++;
}
return count;
}
};
``````