最大公共子串

最大公共子串

https://my.oschina.net/leejun2005/blog/117167

动态转移方程为:

如果xi == yj, 则 c[i][j] = c[i-1][j-1]+1

如果xi ! = yj, 那么c[i][j] = 0

import java.util.Scanner;

public class Test2 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			String str1 = sc.nextLine();
			String str2 = sc.nextLine();
			int[] P = len(str1, str2);
			System.out.println(str1.substring(P[1] - P[0] + 1, P[1] + 1));
		}
	}
	static private int[] len(String str1, String str2) {
		char[] arr1 = str1.toCharArray();
		char[] arr2 = str2.toCharArray();
		int[][] c = new int[arr1.length + 1][arr2.length + 1];
		for (int i = 0; i < arr1.length; i++)
			for (int j = 0; j < arr2.length; j++) {
				if (arr1[i] == arr2[j])
					c[i + 1][j + 1] = c[i][j] + 1;
				else
					c[i + 1][j + 1] = 0;
			}
		int[] P = new int[2]; // max, str1_postition
		for (int i = 1; i < arr1.length + 1; i++)
			for (int j = 1; j < arr2.length + 1; j++)
				if (c[i][j] > P[0]) {
					P[0] = c[i][j];
					P[1] = i - 1;
				}
		return P;
	}

}
posted @ 2017-03-17 20:27  被罚站的树  阅读(159)  评论(0编辑  收藏  举报