動態規劃

給定兩個字符串A和B,返回兩個字符串的最長公共子序列的長度。例如,A=”1A2C3D4B56”,B=”B1D23CA45B6A”,”123456”或者”12C4B6”都是最長公共子序列。

輸入輸出:給定兩個字符串A和B,同時給定兩個串的長度n和m,請返回最長公共子序列的長度。保證兩串長度均小於等於300。

測試樣例:
“1A2C3D4B56”,10,”B1D23CA45B6A”,12
返回:6

代碼實現:

public class LCS {
    public int findLCS(String A, int n, String B, int m) {
        // write code here
        if(n<0||m<0||A==null||B==null){
            return 0;
        }

        int dp [][] = new int[n][m];
        char a[] = A.toCharArray();
        char b[] = B.toCharArray();

        dp[0][0]=a[0]==b[0]?1:0;

        for(int  i = 1 ;i < n;i++){
            if( a[i]==b[0] ){
                dp[i][0] =1 ;
            }else{
                dp[i][0] =dp[i-1][0];
            }
        }

        for(int  i =1  ;i < m;i++){
            if( b[i]==a[0] ){
                dp[0][i] =1 ;
            }else{
                dp[0][i] =dp[0][i-1];
            }
        }

        for(int i =1;i<n;i++){
            for(int j =1;j<m;j++)
            {
                if(a[i]==b[j]){
                    dp[i][j] = dp[i-1][j-1]+1;
                }else{
                    dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j]);
                }
            }

        }


        return dp[n-1][m-1];
    }
}
變形:

給出兩個字符串(可能包含空格),找出其中最長的公共連續子串,輸出其長度。

思路:

DP問題,利用空間換時間,時間複雜度O(NM),空間O(NM)
思想:
創建一張二維表,本來這張表是用來存儲字符A[i]和B[j]是否相等然後將表中(i,j)位置置爲1。
遍歷結束後,計算所有的對角線上連續1的個數,取最大值就是結果。但是現在,換種方法,
遍歷的同時,計算當前斜對角的值,然後用一個變量res記錄最大的值即可。
它的公式爲:如果A[i - 1] == B[j - 1],那麼dp[i][j] = dp[i - 1][j - 1] + 1;
其中dp[0][…]和dp[…][0]都是0,這是初始狀態。
例子:
字符串A:abcde
字符串B:abgde
表1
1 0 0 0 0
0 1 0 0 0
0 0 0 0 0
0 0 0 1 0
0 0 0 0 1
這個不可以直接得到結果,需要再遍歷一次計算。

表2
0 0 0 0 0 0
0 1 0 0 0 0
0 0 2 0 0 0
0 0 0 0 0 0
0 0 0 0 1 0
0 0 0 0 0 2
這個可以直接得到結果,不需要再遍歷一次計算。

代碼實現

import java.util.*;

public class LCS {
    public int findLCS(String A, int n, String B, int m) {
        // write code here
        if(n<0||m<0||A==null||B==null){
            return 0;
        }

        int dp [][] = new int[n][m];
        char a[] = A.toCharArray();
        char b[] = B.toCharArray();

        int res = 0;

        for(int i =0;i<n;i++){
            for(int j =0;j<m;j++)
            {
                if(a[i]==b[j]){
                    dp[i][j] = dp[i-1][j-1]+1;
                    res = Math.max(res,dp[i][j] = dp[i - 1][j - 1] + 1);
                }
            }

        }


        return res;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章