找两个字符串的最长公共子串,这个子串要求在两个原字符串中是连续的。其实这又是一个序贯决策问题,可以用动态规划来求解。我们采用一个二维矩阵来记录中间的结果。这个二维矩阵怎么构造呢?直接举个例子吧:”bab”和”caba”(当然我们现在一眼就可以看出来最长公共子串是”ba”或”ab”)
b a b
c 0 0 0
a 0 1 0
b 1 0 2
a 0 2 0
package pack01;
//最长公共字串
public class test03 {
public static void main(String[] args) {
String str1="1234";
String str2="413749120";
int len = getLCString(str1.toCharArray(), str2.toCharArray());
System.out.println(len);
}
public static int getLCString(char[] str1,char[] str2){
int len1=str1.length;
int len2=str2.length;
int len=0;
int [] c=new int[len2];
for(int i=0;i<len1;i++){
for(int j=len2-1;j>=0;j--){
if(str1[i]==str2[j]){
if(i==0||j==0){
c[j]=1;
}else{
c[j]=c[j-1]+1;
}
}else{
c[j]=0;
}
if(c[j]>len){
len=c[j];
}
}
}
return len;
}
}