最长公共子字符串

给定两个字符串,找到最长的公共子字符串,比如String1=abc12dfe string2=abdec12dfab 所以公共子字符串为c12df。

思路:动态规划,以每个字符为尾字符。

代码:

public class Main {
    //生成dp数组
    public static int[][] getdp(char[] c1, char[] c2) {
        
        int len1 = c1.length;
        int len2 = c2.length;
        
        int[][] dp = new int[len1][len2];
        
        //第一行填充
        for(int j=0; j<len2; j++) {
            if(c1[0] == c2[j]) {
                dp[0][j] = 1;
            }
        }
        
        //第一列填充
        for(int i=0; i<len1; i++) {
            if(c1[i] == c2[0]) {
                dp[i][0] = 1;
            }
        }
        
        for(int i=1; i<len1; i++) {
            for(int j=1; j<len2; j++) {
                if(c1[i] == c2[j]) {
                    dp[i][j] = dp[i-1][j-1]+1;
                }
            }
        }
        
        return dp;
    }
    
    public static String lcs(String s1, String s2) {
        if(s1==null || s1.length()==0 || s2==null || s2.length()==0) {
            return null;
        }
        char[] c1 = s1.toCharArray();
        char[] c2 = s2.toCharArray();
        
        int[][] dp = getdp(c1, c2);
        
        int row = dp.length;
        int col = dp[0].length;
        
        int end = 0;
        int max =0;
        for(int i=0; i<row; i++) {
            for(int j=0; j<col; j++) {
                if(dp[i][j]>=max) {
                    max = dp[i][j];
                    end = i;
                }
            }
        }
        
    return s1.substring(end-max+1,end+1);
    }
    
    public static void main(String[] args) {
        String s1 = "A1234B";
        String s2 = "CD1234";
        
        System.out.println(lcs(s1, s2));
    }
}

 

转载于:https://www.cnblogs.com/loren-Yang/p/7504083.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值