算法12—动态规划算法之:最长公共子序列 & 最长公共子串(LCS)

来源:互联网 发布:金税盘怎么恢复数据 编辑:程序博客网 时间:2024/05/21 03:16

1. 问题描述

子串应该比较好理解,至于什么是子序列,这里给出一个例子:有两个母串

  • cnblogs
  • belong

比如序列bo, bg, lg在母串cnblogs与belong中都出现过并且出现顺序与母串保持一致,我们将其称为公共子序列。最长公共子序列(Longest Common Subsequence, LCS),顾名思义,是指在所有的子序列中最长的那一个。子串是要求更严格的一种子序列,要求在母串中连续地出现。在上述例子的中,最长公共子序列为blog(cnblogs, belong),最长公共子串为lo(cnblogs, belong)。


代码实现

public static int lcs(String str1, String str2) {    int len1 = str1.length();    int len2 = str2.length();    int c[][] = new int[len1+1][len2+1];    for (int i = 0; i <= len1; i++) {        for( int j = 0; j <= len2; j++) {            if(i == 0 || j == 0) {                c[i][j] = 0;            } else if (str1.charAt(i-1) == str2.charAt(j-1)) {                c[i][j] = c[i-1][j-1] + 1;            } else {                c[i][j] = max(c[i - 1][j], c[i][j - 1]);            }        }    }    return c[len1][len2];}

代码实现

public static int lcs(String str1, String str2) {    int len1 = str1.length();    int len2 = str2.length();    int result = 0;     //记录最长公共子串长度    int c[][] = new int[len1+1][len2+1];    for (int i = 0; i <= len1; i++) {        for( int j = 0; j <= len2; j++) {            if(i == 0 || j == 0) {                c[i][j] = 0;            } else if (str1.charAt(i-1) == str2.charAt(j-1)) {                c[i][j] = c[i-1][j-1] + 1;                result = max(c[i][j], result);            } else {                c[i][j] = 0;            }        }    }    return result;}


0 0
原创粉丝点击