- 647. 回文子串
题目:
Given a string s, return the number of palindromic substrings in it.
A string is a palindrome when it reads the same backward as forward.
A substring is a contiguous sequence of characters within the string.
1、暴力解法: 两个for循环i j遍历数组 判断s[i] - s[j]子串是否为palindrome
时间复杂度为O(n^3)
class Solution {
public:
int countSubstrings(string s) {
int n = s.size();
int count = 0;
for(int i = 0; i < n; i++) {
for(int j = i; j < n; j++) {
count += ispalindrome(s, i, j);
}
}
return count;
}
bool ispalindrome(string s, int start, int end) {
if(start == end) return true;
while(start < end) {
if(s[start] != s[end]) return false;
start++;
end--;
}
return true;
}
};
2、动态规划
(1)dp[i][j]含义 :表示s[i] - s[j]是否为Palindrome
(2)递归表达式: 两种情况
<1> s[i] == s[j] -----> j - i <= 1时:dp[i][j] = true ; else 判断dp[i + 1][j - 1]为true则为true
<2> s[i] != s[j] ------> d[i][j] = false;
(3)dp数组 都初始化为 false
(4)遍历顺序: 由于确定dp[i][j]需要确定dp[i + 1][j - 1]
所以需要i从大到小遍历 j需要从小到大遍历
· 设置一个res值(int)记录true的个数
class Solution {
public:
int countSubstrings(string s) {
int n = s.size();
vector<vector<bool>> dp(n, vector<bool>(n, false));
int res = 0;
//遍历顺序 从下到上 从左到右
for(int i = n - 1; i >= 0; i--) {
for(int j = i; j < n; j++) {
if(s[i] == s[j]) {
if(j - i <= 1) {
res++;
dp[i][j] = true;
} else if(dp[i + 1][j - 1]) {
res++;
dp[i][j] =true;
}
}
}
}
return res;
}
};
- 516.最长回文子序列
题目:
Given a string s, find the longest palindromic subsequence's length in s.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
动态规划:
(1)dp[i][j]含义 :表示以s[i] -s[j]字符串中最长回文子序列的长度
(2)递归表达式: 两种情况
<1> s[i] == s[j] -----> dp[i][j] = dp[i + 1][j - 1] + 2
<2> s[i] != s[j] ------> 1)不加入 s[i] ,dp[i][j] = dp[i+1][j]
2)不加入 s[j] , dp[i][j] = dp[i][j - 1]
(3)dp数组 dp[i][i]都初始化为1 其余初始化为0
(4)遍历顺序:需要i从大到小遍历 j需要从小到大遍历
class Solution {
public:
int longestPalindromeSubseq(string s) {
int n = s.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
for(int i = 0; i < n; i++) dp[i][i] = 1;
for(int i = n - 1; i >= 0; i--) {
for(int j = i + 1; j < n; j++) {
if(s[i] == s[j]) {
dp[i][j] = dp[i + 1][j - 1] + 2;
} else {
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
}
}
}
return dp[0][n - 1];
}
};