最长公共子序列问题(LCS)

题目描述

求解两个序列的最长公共子序列的长度。

输入

每组输入包括两行,每行包括一个字符串。

输出

两个序列的最长公共子序列的长度。

样例输入

ACBCDABD
ABDCABA

样例输出

5

备忘录法

import java.util.Scanner;

public class Main {
	static int c[][] = new int[101][101];
	static char x[];
	static char y[];
	
	public static int fun(int i,int j) {
		if(i<0||j<0)
			return 0;
		if(c[i][j]==-1) {
			if(x[i]==y[j])
				c[i][j] = fun(i-1,j-1)+ 1;
			else
				c[i][j] = Math.max(fun(i,j-1),fun(i-1,j));
		}
		return c[i][j];
	}
	
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String str1,str2;
		while(sc.hasNext()) {
			str1 = sc.next();
			str2 = sc.next();
			x = str1.toCharArray();
			y = str2.toCharArray();
			for(int i=0;i<x.length;i++)
				for(int j=0;j<y.length;j++)
					c[i][j] = -1;
			System.out.println(fun(x.length-1,y.length-1));
		}
	}
}

动态规划法(DP)

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String str1,str2;
		char x[],y[];
		int c[][];
		while(sc.hasNext()) {
			str1 = sc.next();
			str2 = sc.next();
			x = str1.toCharArray();
			y = str2.toCharArray();
			c = new int[x.length+1][y.length+1];
			for(int i=0;i<=x.length;i++)
				for(int j=0;j<=y.length;j++) {
					c[i][0] = 0;
					c[0][j] = 0;
				}
			for(int i=0;i<x.length;i++)
				for(int j=0;j<y.length;j++) {
					if(x[i]==y[j])
						c[i+1][j+1] = c[i][j] + 1;
					else
						c[i+1][j+1] = Math.max(c[i+1][j], c[i][j+1]);
				}
			System.out.println(c[x.length][y.length]);
		}
	}
}
发布了12 篇原创文章 · 获赞 1 · 访问量 230

猜你喜欢

转载自blog.csdn.net/qq_46546793/article/details/105371254