方法一:代码较长,理解起来简单,
public class Test2 {
public static void main(String[] args) {
String str1 = "abcwerthelloyuiodef";
String str2 = "cvhellobnm";
// 先看谁长,长的等待短的减少长度作比较
if (str1.length() >= str2.length()) {
compare(str1, str2);
} else {
compare(str2, str1);
}
}
public static void compare(String str1, String str2) {
//定义好较短的字符串最多可以有多少个子串(除了空串)
//并且作为字符串数组的长度创建字符串数组用于存储共同的子串
int maxSonstringnum = str2.length() * (str2.length() + 1) / 2;
String[] sonStrings = new String[maxSonstringnum];
//定义字符串数组下标
int index = -1;
//定义最长字符串数组的下标
int max = 0;
//如果str2本身是str1的子串,那就直接输出
if (str1.indexOf(str2) != -1) {
System.out.println("最大子串是:" + str2);
} else {
//如果不是,遍历,初始位置从0到最大,末位从最大到初始位置+1;遍历所有子串
for (int i = 0; i < str2.length(); i++) {
for (int j = str2.length(); j > i; j--) {
if (str1.indexOf(str2.substring(i, j)) != -1) {
//只要是str1的子串,那就存储。
String s = str2.substring(i, j);
sonStrings[++index] = s;
}
}
}
//假如index没有变,那说明没有共同子串,直接输出
if (index == -1) {
System.out.println("没有共同的子串");
} else {
//如果有,那就按照简单的循环遍历查找最长
for (int i = 1; i < index; i++) {
if (sonStrings[max].length() < sonStrings[i].length()) {
max = i;
}
}
System.out.println("最大子串是:" + sonStrings[max]);
}
}
}
}
方法二是在csdn看到的,感觉非常好用。且代码简洁。附上链接https://blog.csdn.net/xin6yang/article/details/90738316
public class Test {
public static void sp(Object obj){
System.out.println(obj);
}
public static void main(String[] args){
String s1="abcwerthelloyuiodef";
String s2="cvhellobnm";
sp("s1和s2最大相同子串为:"+getMaxSubString(s1,s2));
}
public static String getMaxSubString(String s1,String s2){
String max="",min="";
max=(s1.length()>s2.length())?s1:s2;
min=(max==s1)?s2:s1;
// sp("max="+max+",min="+min);
for(int x=0;x<min.length();x++){
for(int y=0,z=min.length()-x;z!=min.length()+1;y++,z++){
String temp=min.substring(y,z);
// sp(temp);
if(max.contains(temp)){ // if(max.indexOf(temp)!=-1)
return temp;
}
}
}
return "";
}
}
这段代码最主要的就是两个for循环,一开始我并没看懂,。。。debug了一下才明白了这个for循环的作用,实际上就是每次的第一个for循环,规定了获取的子串的长度,从最长开始,一点点减少,长度是在y,z上规定了。比如说10长度,只有一个本身串,而9长度有2个,8长度有3个,,以此类推、找到了就return。就结束代码了。