# 回文串/回文序列系列题：647回文子串个数/ 5最长回文子串/ 516最长回文子序列

## 647. 回文子串：计数字符串中回文子串的个数

1、中心延展法：中心可以取为字母，或两个字母的间隙。

class Solution {
public:
int countSubstrings(string s) {
const int n = s.length();
int ans = 0;
for(int i = 0; i < 2 * n - 1; i++) {
//中心点i一共2n-1个, 偶数序号代表某一个字母为中心(left==right==center),奇数编号代表某一个间隙为中心
int left = i / 2;
int right = left + i % 2;

while(left >= 0 && right < n && s[left] == s[right]) {
ans++;
left--;
right++;
}
}
return ans;
}
};

2、DP方法：dp填充顺序为逐条竖线填充，只填充上三角区域和对角线，因为区间要求 i <= j

class Solution {
public:
int countSubstrings(string s) {
const int n = s.length();
if(n <= 1) return n;

vector<vector<bool>> dp(n, vector<bool>(n, 0));
int sum = 0;
//dp矩阵,逐列填充
//区间[i, j]满足i<=j才行,j为外层
for(int j = 0; j < n; j++) {
for(int i = 0; i <= j; i++) {
if(s[i]==s[j] && (j-i<2 || dp[i+1][j-1])) {
dp[i][j] = true;
sum += 1;
}
}
}
return sum;
}
};

## 5. 最长回文子串

class Solution {
public:
string longestPalindrome(string s) {

const int n = s.length();
//bool dp[n][n]; //初始全为false
vector<vector<bool>> dp(n, vector<bool>(n, false));
int maxLen = 0, start = 0;

for(int j = 0; j < n; j++) {
for(int i = 0; i <= j; i++) {
if(s[i]==s[j] && (j-i<2 || dp[i+1][j-1])) {
dp[i][j] = true;
//maxLen = max(maxLen, j-i+1);
if(j-i+1 > maxLen) {
maxLen = j - i + 1;
start = i;
}
}
}
}
return s.substr(start, maxLen);
}
};
class Solution {
public:
string longestPalindrome(string s) {

const int n = s.length();
int maxLen = 0, start = 0;
for(int i = 0; i < 2*n-1; i++) {
int left = i / 2;
int right = left + i % 2;
while(left >= 0 && right < n && s[left]==s[right]) {
left--;
right++;
}
if(maxLen < right - left - 1) {
maxLen = right - left - 1;
start = left + 1;
}
}
return s.substr(start, maxLen);
}
};

## 516. 最长回文子序列

class Solution {
public:
int longestPalindromeSubseq(string s) {
const int n = s.length();
vector<vector<int>> dp(n, vector<int>(n, 0));

for(int i = n-1; i >= 0; i--) {
dp[i][i] = 1;
for(int j = i+1; j < n; j++) {
if(s[i] == s[j]) {
dp[i][j] = 2 + dp[i+1][j-1];
}
else {
dp[i][j] = max(dp[i+1][j], dp[i][j-1]);
}
}
}
return dp[0][n-1];
}
};

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客