package com.test;
//求两个字符串最长公共字串,
//算法:两个字符串形成一个矩阵,将两个字符不匹配的位置标记为0,c[i][j]中两个字符相匹配的位置标记为n,其中n=c[i-1][j-1]+1,
//其中沿正对角线方向最长的序列为两个字串的最长公共子序列
public class Lcs {
public static void main(String[] args) {
// String s1 = "523311212322324";
// String s2 = "312123223445";
String s1 = "12123221";
String s2 = "312123226";
char[] c1 = s1.toCharArray();
char[] c2 = s2.toCharArray();
Lcs lcs = new Lcs();
System.out.println(lcs.execute(c1, c2));
}
public String execute(char[] c1, char[] c2) {
int[][] c = new int[M][M];
int start = 0; // 记录公共子串的起始位置
int end = 0;// 记录公共子串的结束位置
int maxLength = 0;// 记录最长公共子串的长度
for (int i = 0; i < c1.length; i++) {
for (int j = 0; j < c2.length; j++) {
if (c1[i] == c2[j]) {
if (i == 0 || j == 0) {
c[i][j] = 1;
} else {
c[i][j] = c[i - 1][j - 1] + 1;
// System.out.print(c[i][j]+" ");
}
} else {
c[i][j] = 0;
}
if (c[i][j] > maxLength) {
maxLength = c[i][j];
end = j;
}
}
}
start = end - maxLength + 1;
char[] p = new char[maxLength];
for (int k = start; k <= end; k++) {
p[k - start] = c2[k];
}
return String.valueOf(p);
}
private final int M = 20;
}
求两个字符串最长公共字串
最新推荐文章于 2024-05-06 23:42:46 发布