文字列タイトル-最長の一般的な連続部分文字列

/*
 * 给出两个字符串(可能包含空格),找出其中最长的公共连续子串,输出其长度。
 */
import java.util.Scanner;

public class LongestComSubString {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		String s1 = in.next();
		String s2 = in.next();
		char[] c1 = s1.toCharArray();
		char[] c2 = s2.toCharArray();

		int max = 0;
		int[][] matrix = new int[c1.length + 1][c2.length + 1]; // 定义2维数组
		for (int i = 1; i < matrix.length; i++) {
			for (int j = 1; j < matrix[i].length; j++) {
				if (c1[i - 1] == c2[j - 1]) { // 横向字符与纵向字符相同的时候
					matrix[i][j] = matrix[i - 1][j - 1] + 1; // 该位置的值等于上个对角位置的值加1
					if (matrix[i][j] > max) {// 跟踪最大值
						max = matrix[i][j];
					}
				}
			}
		}
		System.out.println(max);
	}
}

おすすめ

転載: blog.csdn.net/m0_37541228/article/details/77842308