求两个字符串的最长公共子串,要求输入两个字符串,输出他们的最长公共子串,包括长度。

来源:百度知道 编辑:UC知道 时间:2024/05/29 14:03:33
求两个字符串的最长公共子串,要求输入两个字符串,输出他们的最长公共子串,包括长度。

遍历一下就好了,java代码:
public class CommonSubString {

public String search(String s1,String s2)
{
String max = "";
for(int i=0; i<s1.length(); i++)
{
for(int j=i; j<s1.length(); j++)
{
String sub = s1.substring(i,j);
if((s2.indexOf(sub)!=-1)&&sub.length()>max.length())
{
max = sub;
}
}
}
return max;
}

public static void main(String[] args)
{
String s1 = "abcdefghigj";
String s2 = "xyzabcdefigj";
String output = new CommonSubString().search(s1,s2);
System.out.println(output);
}
}

难~
关注