class MyMaxSame{
public static String mymaxsame(String s1, String s2){
String result;
//先让s1指向长串,s2指向短串
if(s1.length()<s2.length()){
result=s1;
s1=s2;
s2=result;
}
for(int i=s2.length();i>0;i--)//相同子串最大长度为s2.length(),从最大长度开
始搜索
for(int j=0;j<s2.length()-i+1;j++){//在S中长度为i的子串有s.length-i+1个
result=s2.substring(j,j+i);
if(s1.contains(result)) return result;
}
return null;
}
public static void main(String[] args){
String s1="abcdebcfbcbc",s2="bcdefgh";
System.out.println("s1="+s1);
System.out.println("s2="+s2);
System.out.println("最大相同子串="+mymaxsame(s2,s1));
}
}
|
|