题目描述:给定两个字符串str1和str2,输出两个字符串的最长公共子串
abcde bebcd == > bcd
实现代码:
实现代码
public class MaxSubString {
public static void main(String[] args){
String st1 = "abcde";
String st2 = "ace";
System.out.println(lstc1(st1,st2));
}
public static int[][] getdp(char[] str1,char[] str2){
int[][] dp = new int[str1.length][str2.length];
for(int i = 0;i < str1.length;i++){
if(str1[i] == str2[0]){
dp[i][0] = 1;
}
}
for(int j = 1;j < str2.length;j++){
if(str1[0] == str2[j]){
dp[0][j] = 1;
}
}
for(int i = 1;i < str1.length;i++){
for(int j = 1;j < str2.length;j++){
if(str1[i] == str2[j]){
dp[i][j] = dp[i-1][j-1] + 1;
}
}
}
return dp;
}
public static String lstc1(String str1,String str2){
if(str1 == null || str2 == null || str1.equals("")||str2.equals("")){
return "";
}
char[] cha1 = str1.toCharArray();
char[] cha2 = str2.toCharArray();
int[][] dp = getdp(cha1,cha2);
int end = 0;
int max = 0;
for(int i = 0;i < cha1.length;i++){
for(int j = 0;j < cha2.length;j++){
if(dp[i][j] > max){
end = i;
max = dp[i][j];
}
}
}
return str1.substring(end - max + 1,end + 1);
}
}
输出结果:
a
标签:子串,String,--,str2,str1,int,length,dp,刷题 From: https://www.cnblogs.com/99kol/p/17456003.html