动态规划

1.经典题目

1.1最大公共子串

public static void main(String[] args){
        int n = f("abcdkkk", "baabcdadabc");
        System.out.println(n);
    }

    static int f(String s1, String s2)
    {
        char[] c1 = s1.toCharArray();
        char[] c2 = s2.toCharArray();

        int[][] a = new int[c1.length+1][c2.length+1];

        int max = 0;
        for(int i=1; i<=s1.length(); i++){
            for(int j=1; j<=s2.length(); j++){
                if(c1[i-1]==c2[j-1]) {
                    a[i][j] = a[i-1][j-1]+1;  //填空
                    if(a[i][j] > max) max = a[i][j];
                }
            }
        }

        for (int i = 0; i < s1.length(); i++) {
            for (int j = 0; j < s2.length(); j++) {
                System.out.print(a[i][j]+" ");
            }
            System.out.println();
        }

        return max;
    }

1.2最长公共子序列(不要求连续)

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String str1 = scanner.nextLine().toLowerCase();
            String str2 = scanner.nextLine().toLowerCase();
            System.out.println(findLCS(str1, str1.length(), str2, str2.length()));
        }
    }

    public static int findLCS(String A, int n, String B, int m) {
        int[][] dp = new int[n + 1][m + 1];
        System.out.println(n);
        System.out.println(m);
        //如果匹配到相同的字符,则dp[i][j] = dp[i - 1][j - 1] + 1;
        //如果没有匹配到相同的字符,则,使当前dp[i][j]为目前dp数组中的最大值,
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (A.charAt(i - 1) == B.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = dp[i - 1][j] > dp[i][j - 1] ? dp[i - 1][j] : dp[i][j - 1];
                }
            }
        }

        for (int i = 0; i < A.length(); i++) {
            for (int j = 0; j < B.length(); j++) {
                System.out.print(dp[i][j]+" ");
            }
            System.out.println();
        }
        return dp[n][m];
    }
posted @ 2021-04-07 17:05  木有呂朋友  阅读(25)  评论(0编辑  收藏  举报