最长的公共子串
题目描述
给定两个字符串str1和str2,输出两个字符串的最长公共子串,如果最长公共子串为空,输出-1。
输入描述:
输入包括两行,第一行代表字符串srr1,第二行代表字符串str2。\left( 1\leq length(str1),length(str2) \leq 5000 \right)(1≤length(str1),length(str2)≤5000)
输出描述:
输出包括一行,代表最长公共子串。
示例1
输入
复制
1AB2345CD 12345EF
输出
复制
2345
// 求两个字符串的最长的公共子串。
import java.util.Scanner;
public class Main{
public static String common(String s1, String s2) {
int[][] dp = new int[s1.length()][s2.length()];
for(int j = 0;j<s2.length();j++) {
if(s1.charAt(0)==s2.charAt(j)) {
dp[0][j] = 1;
}
}
for(int j= 0;j<s1.length();j++) {
if(s1.charAt(j)==s2.charAt(0)) {
dp[j][0]= 1;
}
}
int maxLen =0, maxEnd = 0;
for(int i=1;i<s1.length();i++) {
for(int j=1;j<s2.length();j++) {
if(s1.charAt(i)==s2.charAt(j)) {
dp[i][j] = dp[i-1][j-1]+1;
}
if(dp[i][j]>maxLen){
maxLen = dp[i][j];
maxEnd = i;
}
}
}
StringBuilder sb = new StringBuilder();
if(maxLen == 0) {
return "-1";
}
else {
for(int i= maxEnd-maxLen+1;i<= maxEnd;i++){
sb.append(s1.charAt(i));
}
}
return sb.toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str1 = sc.next();
String str2 = sc.next();
System.out.println(common(str1,str2));
}
}