最长公共子串的长度

/*
 * 编写函数,获取两段字符串的最长公共子串的长度,
 * 例如: 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));
	}
}



                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值