首页 > 试题广场 >

最长公共子串

[编程题]最长公共子串
  • 热度指数:7861 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定两个字符串str1和str2,输出两个字符串的最长公共子串,如果最长公共子串为空,输出-1。

输入描述:
输入包括两行,第一行代表字符串srr1,第二行代表字符串str2。


输出描述:
输出包括一行,代表最长公共子串。
示例1

输入

1AB2345CD
12345EF

输出

2345

备注:
时间复杂度,额外空间复杂度。(n可以为其中任意一个字符串长度)

import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str1 = sc.nextLine();
String str2 = sc.nextLine();
int m = str1.length();
int n = str2.length();
char[] ch1 = str1.toCharArray();
char[] ch2 = str2.toCharArray();
int[][] dp = new int[m + 1][n + 1];
for(int i = 0; i <= m; i++) {
dp[i][0] = 0;
}
for(int j = 0; j <= n; j++) {
dp[0][j] = 0;
}
//二维dp数组,动态规划
int max = 0;
int index = 0;
for(int i = 1; i <= m; i++) {
for(int j = 1; j <= n; j++) {
if(ch1[i - 1] == ch2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
}else {
dp[i][j] = 0;
}
if(dp[i][j] > max) {
index = i;
max = dp[i][j];
}
}
}
if(max == 0) {
System.out.println(-1);
}else {
String res = str1.substring(index - max, index);
System.out.println(res);
}
}
}

发表于 2022-04-17 10:09:34 回复(0)

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
            String str1 = sc.nextLine().trim();
            String str2 = sc.nextLine().trim();
            System.out.println(maxCommonStr(str1, str2));
        sc.close();
    }

    private static String maxCommonStr(String str1, String str2) {
        if (str1 == null || str2 == null) {
            return "-1";
        }
        int len1 = str1.length();
        int len2 = str2.length();
        int[][] dp = new int[len1 + 1][len2 + 1];
        int lmax = 0;
        int pmax = 0;
        for (int i = 1; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {
                if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                    if(dp[i][j] > lmax)
                    {
                        lmax = dp[i][j];
                        pmax = i;
                    }

                }
            }
        }
        StringBuffer res = new StringBuffer();
        for (int i = pmax  - lmax  ; i < pmax ; i++) {
            res.append(str1.charAt(i));
        }
        if(lmax == 0)
        {
            return "-1";
        }
        return res.toString();

    }
}
发表于 2020-03-26 22:08:41 回复(0)