动态规划:最大子序列和最大子串 Java

    最大子序列是指子串与母串相比顺序不变且子串的字符与母串相等。这里有字符串str1 = CNBLOG , str2 = BELONG,则它的最大子序列为BLOG,虽然N也相等但是顺序不对。最大子串指str1与str2相同且连续的部分,也就是LO。

   求解最大子序列,先定义最大子序列长度LCS[i,j] = LCS[i-1,j] + 1 (str1[i]==str2[j]) 或 LCS[i,j] = max{LCS[i,j-1],LCS[i-1,j]} (str1 != str2)。此时,LCS[str1.length,str2.length]的值为最大子序列的长度,如何得到最大子序列,我们观察一下LCS数组:

动态规划:最大子序列和最大子串 Java_第1张图片

为了保证有序,从j=1开始,只要LCS[i,j] > LCS[i,j-1] 且 LCS[i,j]>LCS[i-1,j]那么 str1[i-1]的值必然与str2[j-1]的值相等,此时需记住j的值(为保证有序)在下一次比较时从j后的值开始比较大小。

   求解最大子串,先定义最大子串长度 LSTR[i,j] = LSTR[i-1,j-1] + 1 (str1[i] == str2[j]) 或 LSTR[i,j] = 0 (str1[i] != str2[j]),然后找到LSTR的最大值,最大值为最长子串。

动态规划:最大子序列和最大子串 Java_第2张图片

   以下为求解最大子序列和最大子串的可执行Java代码:

package dyfu.algorithm;

public class DP_LCS {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str1 = "CNBLOG";
		String str2 = "BELONG";

		int[][] lcs = getLCSAmount(str1, str2);
		System.out.println("the longest common subsequence's length is "
				+ lcs[str1.length()][str1.length()]);

		System.out.println("the longest common subsequence is "
				+ getLCSStr(lcs, str1));
		
		System.out.println("the longest common string is " + getLString(getLStringArr(str1,str2),str1));
		

	}

	//获取最长子序列动态规划数组
	public static int[][] getLCSAmount(String str1, String str2) {

		int x = str2.length() + 1;
		int y = str1.length() + 1;
		int[][] LCS = new int[y][x];

		for (int i = 0; i < y; i++)
			LCS[i][0] = 0;
		for (int j = 0; j < x; j++)
			LCS[0][j] = 0;

		for (int i = 1; i < y; i++)
			for (int j = 1; j < x; j++) {
				if (str1.charAt(i-1) == str2.charAt(j-1)) {
					LCS[i][j] = LCS[i - 1][j] + 1;
				} else {
					LCS[i][j] = LCS[i - 1][j] >= LCS[i][j - 1] ? LCS[i - 1][j]: LCS[i][j - 1];
				}
			}

		return LCS;
	}

	//获取最长子序列
	public static String getLCSStr(int[][] lcss, String str1) {

		int x = lcss[0].length;
		int y = lcss.length;
		StringBuffer tmp = new StringBuffer();
		int a = 1;
		for (int i = 1; i < x; i++)
			for (int j = a; j < y; j++) {
				if(lcss[j][i] > lcss[j][i-1] && lcss[j][i] > lcss[j-1][i]) {
					tmp.append(str1.charAt(j-1));
					a = j+1;
				}
			}

		return tmp.toString();
	}
	
	//获取最长子串数组
	public static int[][] getLStringArr(String str1,String str2) {
		
		int x = str2.length()+1;
		int y = str1.length()+1;
		
		int[][] strArray = new int[y][x];
		
		for(int i=0;i max) {
					max = str[i][j];
					tmpx = j;
					tmpy = i;
				}
			}
		System.out.println("tmpx = "+tmpx);
		System.out.println("tmpy = "+tmpy);
		StringBuffer lstr = new StringBuffer();
		for(int k=tmpy-max;k

以下为执行结果:

动态规划:最大子序列和最大子串 Java_第3张图片

你可能感兴趣的:(算法)