最长公共子序列问题

动态规划解决最长公共子序列的问题

动态规划:将大问题分析划分为小问题,解决小问题即解决了大问题

Java 实现代码如下:正确性仍需进一步验证

 public static String commonStr(char[] ch1,char[] ch2,int i,int j){
        if(i < 0 || j < 0){
            return "";
        }
        if(ch1[i] == ch2[j]){
            char ch = ch1[i];
            return commonStr(ch1,ch2,--i,--j) + ch;
        }else{
            return maxStr(commonStr(ch1,ch2,i,--j),commonStr(ch1,ch2,--i,j));
        }

    }

    public static String maxStr(String s1,String s2){
        return s1.length() > s2.length() ? s1:s2;
    }

    public static void main(String[] args) {

        char[] ch1 = {'b','d','c','a','b','a'};

        char[] ch2 = {'a','b','c','b','d','a','b'};

        System.out.println(commonStr(ch1,ch2,ch1.length-1,ch2.length-1));


    }

 暴力查找最长公共字串

public static int commonStr(char[] ch1,char[] ch2){
        int result = 0;
        for(int i=0;i<ch1.length;i++){
            for(int j=0;j<ch2.length;j++){

                int len = 0;
                int n = i;
                int m = j;
                while(n<ch1.length && m < ch2.length && ch1[n] == ch2[m]){
                    len++;
                    n++;
                    m++;
                }
                result = Math.max(result,len);
            }
        }
        return result;
    }


    public static void main(String[] args) {

        char[] ch1 = {'a','b','c','d','e','f'};

        char[] ch2 = {'a','b','c','b','d','a','b'};

        System.out.println(commonStr(ch1,ch2));

    }

 

posted @ 2022-01-26 14:53  byebai95  阅读(26)  评论(0编辑  收藏  举报