找两个字符串的最长公共子序列的长度

简述:

找两个字符串的最长公共子序列的长度


例如

String str1 = “caaac”;

String str2 = "bbdaaaca";


两者最长公共子序列就是aaac 为4


代码实现:

package offer;

public class LongestCommonSubsequence {
	public static void main(String[] args) {
		LongestCommonSubsequence obj = new LongestCommonSubsequence();
		String str1 = "caaac";
		String str2 = "bbdaaaca";
		System.out.println("LongestCommonSubsequence: " + obj.getMaxLength(str1, str2));
	}
	public int getMaxLength(String str1, String str2){
		int m = str1.length();
		int n = str2.length();
		int resultArray[][] = new int[m + 1][n + 1];
		int maxLength = 0;
		//initialize the raw array
		for(int i = 1; i <= m; i++)
			for(int j = 1; j <= n; j++){
				if(str1.charAt(i - 1) == str2.charAt(j - 1) 
						&& resultArray[i - 1][j - 1] != 0 )
					resultArray[i][j] = 1 + resultArray[i - 1][j - 1];
				else if(str1.charAt(i - 1) == str2.charAt(j - 1))
					resultArray[i][j] = 1;
				else
					resultArray[i][j] = 0;
			}
		//output the resultArray
		System.out.println("resultArray: ");
		for(int i = 1; i <= m; i++){
			for(int j = 1; j <= n; j++){
				System.out.print(resultArray[i][j] + ", ");
			}
			System.out.println();
		}
		
		for(int i = 0; i <= m; i++)
			for(int j = 0; j <= n; j++){
				if(resultArray[i][j] > maxLength)
					maxLength = resultArray[i][j];
			}
		return maxLength;
	}
}

输出:


但是由于只要保留斜对角线的resultArray[i - 1][ j - 1] 所以没有必要声明整个二维数组 ,只要保留一个维度就可以了

, 最后遍历一下得到每一次生成行的最大值,下面就是按照这个思想实现的算法

代码2(只保留一维数组)

package offer;

public class LongestCommonSubsequence {
	public static void main(String[] args) {
		LongestCommonSubsequence obj = new LongestCommonSubsequence();
		String str1 = "caaac";
		String str2 = "bbdaaaca";
		System.out.println("LongestCommonSubsequence: " + obj.getMaxLength(str1, str2));
	}
	public int getMaxLength(String str1, String str2){
		int m = str1.length();
		int n = str2.length();
		//use tempArray to restore the data
		int tempArray[] = new int[n];
		int maxLength = 0;
		for(int i = 0; i < m; i++){
			for(int j = n - 1; j >= 0; j--){
				if(str1.charAt(i) != str2.charAt(j))
					tempArray[j] = 0;
				else{
					tempArray[j] = tempArray[j - 1] + 1;
					if(tempArray[j] > maxLength)
						maxLength = tempArray[j];
				}
			}
			if(str1.charAt(i) != str2.charAt(0)){
				tempArray[0] = 0;
				if(tempArray[0] > maxLength)
					maxLength = tempArray[0];
			}
			/**
			 * output for test
			 ****************************************/
			for(int k = 0; k < n; k++)
				System.out.print(tempArray[k] + ", ");
			System.out.println();
			/****************************************/
			
		}
		return maxLength;
	}
}

输出:(循环单行输出)




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值