此算法为最长公共子串(Longest Common Substring),区别于最长公共子序列(Longest Common Sequence),后者的算法请见Java_动态规划|回溯|最长公共子序列(Longest Common Sequence)|LCS
/**
* 核心算法:
* 当i=0||j=0时,c[i,j]=0
* 当xi=yj时,c[i,j]=c[i-1,j-1]+1
* 当xi!=yj时,c[i,j]=0
*
* 算例中考虑了会出现多个最长公共子串的情况
* 且所有LCS均输出
*
* @author Chill Lyn
*
*/
class LongestCommonSubstring {
public static void main(String[] args) {
// 定义两个字符串
String x = "abcde";
String y = "cdcdeabc";
lcs(x, y);
}
public static void lcs(String x, String y) {
// 定义动态规划二维数组
int[][] c = new int[x.length() + 1][y.length() + 1];
// 最长公共子串长度
int maxLength = 0;
// 可能出现的最长公共子串的个数
int count = 1;
// 用于存储最长公共子串末尾元素索引的数组