[编程题] 最长公共连续子串(美团点评2017秋招)

时间限制:1秒
空间限制:32768K

给出两个字符串(可能包含空格),找出其中最长的公共连续子串,输出其长度。
输入描述:输入为两行字符串(可能包含空格),长度均小于等于50.
输出描述:输出为一个整数,表示最长公共连续子串的长度。

输入例子1:
abcde
abgde
输出例子1:
2

//动态规划经典解法
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s1 = sc.nextLine();
        String s2 = sc.nextLine();
        char[] c1 = s1.toCharArray();
        char[] c2 = s2.toCharArray();
        System.out.println(getdp(c1, c2));
    }
    public static int getdp(char[] s1, char[] s2) {
        int[][] dp= new int[s1.length][s2.length];
        for(int i = 0; i < s1.length; i++) {
            if(s1[i] == s2[0]) {
                dp[i][0] = 1;
            }
        }
        for(int j = 1; j < s2.length; j++) {
            if(s1[0] == s2[j]) {
                dp[0][j] = 1;
            }
        }
        for(int i = 1; i < s1.length; i++) {
            for(int j = 1; j < s2.length; j++) {
                if(s1[i] == s2[j]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                }
            }
        }
        int max = 0;
        for(int i = 0; i < s1.length; i++) {
            for(int j = 0; j < s2.length; j++) {
                if(dp[i][j] > max) {
                    max = dp[i][j];
                }
            }
        }
        return max;
    }
}

猜你喜欢

转载自blog.csdn.net/u013015065/article/details/78962339