给出两个字符串,找到最长公共子串,并返回其长度。
注意事项
子串的字符应该连续的出现在原字符串中,这与子序列有所不同。
样例
给出A=“ABCD”,B=“CBCE”,返回 2
public class n13longestComSubstring {
public static void main(String[] args) {
String a="abcd";
String b="kbco";
System.out.println(longestComSubstring(a,b));
}
public static int longestComSubstring(String a,String b){
int [][]c=new int[a.length()+1][b.length()+1];
for(int i=1;i<=a.length();i++){
for(int j=1;j<=b.length();j++){
if(a.charAt(i-1)==b.charAt(j-1)){
c[i][j]=c[i-1][j-1]+1;
}else{
c[i][j]=0;
}
}
}
int max=0;
for(int i=0;i<=a.length();i++)
for(int j=0;j<b.length();j++){
max=Math.max(max, c[i][j]);
}
return max;
}
}