最长回文子串

class Solution {
    public String longestPalindrome(String s) {
        if(s.equals("") || s == null) return "";
int length = s.length();
boolean[][] dp = new boolean[length][length];
int start = 0;
int end = 0;
int res = 1;
for(int i = length - 1; i >= 0; i --){
   
    for(int j = i ; j < length; j ++){
        if((j - i <= 2||dp[i+1][j-1])&&s.charAt(i)==s.charAt(j)){
            dp[i][j] = true;
        }
       if(dp[i][j]&&j - i + 1 > res){
           res = j - i + 1;
           start = i;
           end = j;
       }
     
    }
}
return s.substring(start,end+1);
    }
}

最长回文子序列

class Solution {
    public int longestPalindromeSubseq(String s) {
if(s == null || s.length()==0)
return 0;
int n = s.length();
int[][] dp = new int[n][n];
dp[n-1][n-1] = 1;
for(int i = n-2; i >=0; i --){
    dp[i][i] = 1;
    for(int j = i+1; j < n; j ++){
        if(s.charAt(i)==s.charAt(j)){
         
            dp[i][j] = Math.max(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][n-1];
    }
}

最长上升子序列

class Solution {
    public int lengthOfLIS(int[] nums) {
if(nums.length == 0) return 0;
int length = nums.length;
int[] dp = new int[length];
int res = 0;
Arrays.fill(dp,1);
for(int i = 0; i < length; i ++){
    for(int j = 0 ;j < i; j ++){
        if(nums[i] > nums[j]){
            dp[i] = Math.max(dp[i],dp[j]+1);
        }
    }
    res = Math.max(res,dp[i]);
}
return res;
    }
}

最长公共子序列

class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length();
int n = text2.length();
int[][] dp =new int[m+1][n+1];
dp[0][0] = 0;
for(int i = 1; i <= m; i ++){
    dp[i][0] = 0;
}
for(int i = 1; i <= n; i ++){
    dp[0][i] = 0;
}
for(int i = 1; i <= m; i++){
    for(int j = 1; j <= n; j ++){
        if(text1.charAt(i-1)==text2.charAt(j-1)){
            dp[i][j] = dp[i-1][j-1]+1;
        }else{
            dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
        }
    }
}
return dp[m][n];
    }
}

 

posted on 2020-05-07 15:48  Moonshoterr  阅读(119)  评论(0编辑  收藏  举报