求解最大公共子字符串问题

/**
 * 内容描述:求解最大公共子字符串问题
 *          请设计函数,返回指定存在于两个字符串中最大的子字符串(如果存在多个相同长度的,只返回第一个)
 * 创建人:yang.liu
 * 创建时间:2019/7/4 12:53
 * 版本:1.0
 */
public class MaxCommonStringSample {

    public static String getMaxCommonString(String str1, String str2) {
        if (null == str1 && null == str2) {
            return "";
        }
        char[] c1 = str1.toCharArray();
        char[] c2 = str2.toCharArray();
        int[][] comp = new int[c1.length][c2.length];

        //max记录相同子串的最大长度
        // m记录最长公共字符串的最后位置,用来找最大字符串
        // n记录最长公共字符串的开始位置,用来找最大字符串
        /**
         * str1 = "acdedeg";
         * str2 = "abcdefg";
         * 比较结果是最大长度的公共字符串是3
         *    a b c d e f g
         *  a 1 0 0 0 0 0 0
         *  c 0 0 1 0 0 0 0
         *  d 0 0 0 2 0 0 0
         *  e 0 0 0 0 3 0 0
         *  d 0 0 0 1 0 0 0
         *  e 0 0 0 0 2 0 0
         *  g 0 0 0 0 0 0 1
         */
        int max = 0, m = -1, n = -1;
        for (int i = 0; i < c1.length; i++) {
            for (int j = 0; j < c2.length; j++) {
                if (c1[i] != c2[j]) {
                    // 矩阵位置不同字符,值设为1
                    comp[i][j] = 0;
                } else {
                    // 矩阵位置相同字符,值为左上角的值加1.
                    if (i == 0 || j == 0) {
                        comp[i][j] = 1;
                    } else {
                        comp[i][j] = comp[i - 1][j - 1] + 1;
                    }

                    if (comp[i][j] > max) {
                        max = comp[i][j];
                        m = i;
                        n = j;
                    }
                }

            }
        }

        StringBuffer commonStr = new StringBuffer();
        while (m >=0 && n >= 0 && comp[m][n] > 0) {
            commonStr.append(c1[m]);
            m--;
            n--;
        }
        return commonStr.reverse().toString();
    }

    public static void main(String[] args) {
        String str1 = "aaa";
        String str2 = "ebc";

        String s = getMaxCommonString(str1, str2);
        System.out.println(s);

    }

}

/**
 * 欢迎评论、留言、发表看法。谢谢!
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值