最长公共连续子串
题目
牛牛有两个字符串(可能包含空格),牛牛想找出其中最长的公共连续子串,希望你能帮助他,并输出其长度。
输入描述
输出描述
示例
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| import java.util.Scanner;
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String s1 = scanner.nextLine(); String s2 = scanner.nextLine(); int m = s1.length(); int n = s2.length(); char[] array1 = s1.toCharArray(); char[] array2 = s2.toCharArray(); int[][] dp = new int[m + 1][n + 1]; int maxLen = 0;
for (int i = 1; i <= m; i++){ for (int j = 1; j <= n; j++){ if (array1[i - 1] == array2[j - 1]){ dp[i][j] = dp[i-1][j-1] + 1; maxLen = Math.max(maxLen,dp[i][j]); }else { dp[i][j] = 0; } } } System.out.println(maxLen); } }
|