回文子串(最长回文字串
Dp[i][j]表示i到j是否是回文字串,左闭右闭区间
回文字串三种情况:1 i=j 是 2.i与j相差一个位置是
- i与j相差很多个,判断区间里是否是回文字串
遍历顺序由递推公式来决定,所以可以画图看看
class Solution {
public int countSubstrings(String s) {
char[] c1=s.toCharArray();
int len=c1.length;
int res=0;
boolean[][] dp=new boolean[len][len];//dp[i][j]表示i到j是这个范围是不是回文字串
for(int i=len-1;i>=0;i--){
for(int j=i;j<len;j++){
if(c1[i]==c1[j]){//先判断所指向的元素是否相等
if(j-i<=1){
dp[i][j]=true;
res++;
}else if(dp[i+1][j-1]){
dp[i][j]=true;
res++;
}
}
}
}
return res;
}
}
回文子串(最长回文子序列 ,可以不连续
求最长回文子序列的长度,如果i和j指向的数相等则+2,不能则取最大值(i+1,j-1)
初始化,i和j相等时为1
class Solution {
public int longestPalindromeSubseq(String s) {
char[] c=s.toCharArray();
int len=c.length;
int[][] dp=new int[len][len];//i到j的最长回文子序列
for(int i=len-1;i>=0;i--){
dp[i][i]=1;//初始化
for(int j=i+1;j<len;j++){
if(c[i]==c[j]){
dp[i][j]=dp[i+1][j-1]+2;
}else{
dp[i][j]=Math.max(dp[i+1][j],dp[i][j-1]);
}
}
}
return dp[0][len-1];
}
}