动态规划--最长公共字序列

package com.xjj.algorithm;

import java.util.Scanner;
/*----最长公共子序列--动态规划----
 * 1.用dp[i][j] 表示 A 的  i 位与 B 的 j 位之前的公共字序列的长度,则其满足:
 * 		a.当A[i]=B[i] 时,dp[i][j] = dp[i-1][j-1] + 1;
 * 		B.当不相等时,继承自   max(dp[i-1][j],dp[i-1][j])
 * 2.递推:从边界向目标进行;
 * 
 * */
public class LCS {
	
	public int dp_method(char[] a, char[] b){
		int na = a.length;
		int nb = b.length;
		int[][] dp = new int[na][nb];
		
		//初始化设置边界
		for(int i = 0; i < na; i++)
			if (a[i] == b[0]) 
				dp[i][0] = 1;
		for(int i = 0; i < nb; i++)
			if (a[0] == b[i]) 
				dp[0][i] = 1;
		
		//遍历每一个元素
		for(int i = 1; i < na; i++)
			for(int j = 1; j < nb; j++){
				if (a[i] == b[j] )
					dp[i][j] = dp[i-1][j-1] + 1;
				else
					dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j]);
			}
		return dp[na-1][nb-1];
	}

	public static void main(String[] args) {
		System.out.println();

		Scanner scanner = new Scanner(System.in);
		String s1 = scanner.nextLine();
		String s2 = scanner.nextLine();
		
		String[] strings = s1.split("");
		
		char[] cs1 = s1.toCharArray();
		char[] cs2 = s2.toCharArray();
		LCS lcs = new LCS();
		System.out.println(lcs.dp_method(cs1, cs2));
		

	}

}

猜你喜欢

转载自blog.csdn.net/jiejiexiao/article/details/79659272