51Nod 1006 最長公共子序列Lcs

callmexiaolu發表於2018-07-18

動態規劃,轉移方程為:字元相同dp[i][j]=dp[i-1][j-1]+1;不同dp[i][j]=MAX(dp[i-1][j],dp[i][j-1])

最後根據MAX值和dp[i][j](dp[i][j]始終是最大值)來判斷哪個字元相同,則存進stringbuilder中。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class LCS {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String s1 = in.readLine();
        String s2 = in.readLine();

        char[] str1 = s1.toCharArray();
        char[] str2 = s2.toCharArray();

        int len1 = str1.length;
        int len2 = str2.length;
        int[][] dp = new int[len1+1][len2+1];
      
        //計算DP值
        for (int i = 1; i <=len1; i++) {
            for (int j = 1; j <=len2; j++) {
                if (str1[i-1] == str2[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]);
            }
        }
        StringBuilder stringBuilder = new StringBuilder();//因為String經常更改會導致效能低下,StringBuilder經常改動效率最高
        int k = 0,i = len1 , j = len2;
        //System.out.println(dp[len1][len2]);
        while (k != dp[len1][len2]){
            if (dp[i-1][j] == dp[i][j])//當前字元與另一字串相對應字元不同
                i--;
            else if (dp[i][j-1] == dp[i][j])//當前字元與另一字串相對應字元不同
                j--;
            else {
                if (dp[i][j] != dp[i-1][j-1]) {//當前字元與另一字串相對應字元相同
                    stringBuilder.insert(0, str1[i - 1]);//存進去
                    k++;
                }
                i--;
                j--;
            }
        }
        System.out.println(stringBuilder.toString());
    }
}

 

相關文章