/*
* 编写函数,获取两段字符串的最长公共子串的长度,
* 例如: S1= GCCCTAGCCAGDE
* S2= GCGCCAGTGDE
* 这两个序列的最长公共子串是GCCAG,也就是说返回值为5
* Author: Huixing Fang
*/
public class LongestSubString {
public LongestSubString() {}
public static int LCS(String str1, String str2) {
if (str1 == null || str2 == null) return 0;// 若其一为空则设返回值为0
if (str1.length() == 0 || str2.length() == 0) return 0;// 若其一长度为0,则设返回值为0
char[] cs1 = str1.toCharArray();// 转成数组,当然也可以不用转,个人喜好了
char[] cs2 = str2.toCharArray(); // 转成数组
// 定一个2维数组,保存两个字符串各字符间的关系,默认为全0,表示两两不相等
int[][] lcsarray = new int[str1.length()][str2.length()];
int max = 0; //最大公共字串长度
for (int i = 0; i < str1.length(); i++) {
for (int j = 0; j < str2.length(); j++) {
if (cs1[i] == cs2[j]) {
// 如果相等则设置为>=1的整数
// 若前字串长度>=1则增加新公共串串长度+1
if (i - 1 >= 0 && j - 1 >= 0 && lcsarray[i - 1][j - 1] > 0)
lcsarray[i][j] = lcsarray[i - 1][j - 1] + 1;
else lcsarray[i][j] = 1;// 若前无字串,则此串为新开始的串,设置为1,后续若有则增1
if (lcsarray[i][j] > max) max = lcsarray[i][j]; // 更新最大公共字串长度
}
else lcsarray[i][j] = 0; // 若不是公共部分则设置为0,以区分于公共字串
}
}
return max; // 返回结果
}
public static void main(String[] args) {
// 两个测试串
String str1 = "GCCCTAGCCAGDE";
String str2 = "GCGCCAGTGDE";
System.out.println(LongestSubString.LCS(str1, str2));
}
}最长公共子串的长度
最新推荐文章于 2022-02-05 14:39:42 发布
本文介绍了一种算法,用于计算两个给定字符串之间的最长公共子串长度,通过创建一个二维数组来记录两个字符串各字符间的对应关系,并在遍历过程中更新最大公共子串长度。
2473

被折叠的 条评论
为什么被折叠?



