代买随想录二刷day57
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
一、力扣647. 回文子串
class Solution {
public int countSubstrings(String s) {
int n = s.length();
boolean[][] dp = new boolean[n][n];
int res = 0;
for(int i = n-1; i >= 0; i --){
for(int j = i; j < n; j ++){
if(s.charAt(i) == s.charAt(j)){
if(j -i <= 1){
res ++;
dp[i][j] = true;
}else if(dp[i+1][j-1]){
res ++;
dp[i][j] = true;
}
}
}
}
return res;
}
}
class Solution {
public int countSubstrings(String s) {
int res = 0;
for(int i = 0; i < s.length(); i ++){
res += fun(i,i,s);
res += fun(i,i+1,s);
}
return res;
}
public int fun(int start, int end, String s){
int res = 0;
while(start >= 0 && end < s.length()){
if(s.charAt(start) != s.charAt(end)){
return res;
}
start --;
end ++;
res ++;
}
return res;
}
}
二、力扣516. 最长回文子序列
class Solution {
public int longestPalindromeSubseq(String s) {
int n = s.length();
int[][] dp = new int[n][n];
for(int i = n-1; i >= 0; i --){
for(int j = i; j < n; j ++){
if(s.charAt(i) == s.charAt(j)){
if(j - i <= 1){
dp[i][j] = j-i+1;
}else{
dp[i][j] = dp[i+1][j-1] + 2;
}
}else{
dp[i][j] = Math.max(dp[i][j-1], dp[i+1][j]);
}
}
}
return dp[0][n-1];
}
}