求两个字符串的最长公共子串

首先分清出最长公共子串与最长公共子序列的区别:

找两个字符串的最长公共子串,这个子串要求在原字符串中是连续的。而最长公共子序列则并不要求连续。
比如说:两个字符串“asdfghjkl”和“adghjkl”。最长公共子串指的是:“ghjk”,而最长共子序列指的是:“adghjkl”。
由于寻找公共子序列比较简单,在这里就直接上代码了。
参考代码:

public class LCS {
    public static void main(String[] args) {
        String str1 = "asdfghjkl";
        String str2 = "adghjkl";
        String comStr = getLcs(str1,str2);
        System.out.println("最大子串为:" + comStr + " ,长度为:" + comStr.length());
    }

    private static String getLcs(String str1, String str2) {
        int len1 = str1.length();
        int len2 = str2.length();
        int minlen = len1 < len2 ? len1 : len2;
        int max = 0, index = 0;
        String minstr = len1 < len2 ? str1 : str2;
        String maxstr = len1 < len2 ? str2 : str1;
        for(int i = 0; i < minlen; i++){
            for(int j = i + 1;j < minlen + 1; j++){
                String temp = minstr.substring(i, j);
                if(maxstr.contains(temp) && temp.length() > max){
                    max = temp.length();
                    index = i;
                }
            }
        }
        return minstr.substring(index, max + index);
    }
}

代码比较简单,在这里并不作太多的解释。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值