首页 > 试题广场 >

最长公共连续子串

[编程题]最长公共连续子串
  • 热度指数:6604 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
牛牛有两个字符串(可能包含空格),牛牛想找出其中最长的公共连续子串,希望你能帮助他,并输出其长度。

输入描述:
输入为两行字符串(可能包含空格),长度均小于等于50.


输出描述:
输出为一个整数,表示最长公共连续子串的长度。
示例1

输入

abcde
abgde

输出

2
import java.util.Scanner;

public class Main {
    public int findLength(String s1, String s2) {
        char[] A = s1.toCharArray();
        char[] B = s2.toCharArray();
        int n = A.length;
        int m = B.length;
        int[][] dp = new int[n + 1][m + 1];
        int res = 0;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (A[i - 1] == B[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                    res = Math.max(res, dp[i][j]);
                }
            }
        }
        return res;
    }
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        String s1=cin.nextLine();
        String s2 = cin.nextLine();
        System.out.println(new Main().findLength(s1,s2));
    }
}
/*
abcde
abgde
2

asdfas
werasdfaswer
 6
 */


发表于 2020-06-16 12:41:43 回复(0)

热门推荐

通过挑战的用户