String运用——查找两个字符串的最大子串

//查找两个字符串的最大子串。

String str1="dsajdwefnadsjaw";
String str2="adwefb";


private static String getMaxSameStr(String str1, String str2) {
int length1 = str1.length();
int length2 = str2.length();
boolean flag=(length1>length2);
int maxlength=0;
int first=0;
int last=0;
if(flag){
for(int firstIndex=0;firstIndex<length2;firstIndex++){
for (int lastIndex=length2-1;lastIndex>firstIndex;lastIndex--){
if(str1.contains(str2.substring(firstIndex,lastIndex+1))){
if(str2.substring(firstIndex,lastIndex+1).length()>maxlength){
maxlength=str2.substring(firstIndex,lastIndex+1).length();
first=firstIndex;
last=lastIndex+1;
}

}
}
}
return str2.substring(first,last+1);
}else{
first=0;
last=0;
for(int firstIndex=0;firstIndex<length1;firstIndex++){
for (int lastIndex=length1-1;lastIndex>firstIndex;lastIndex--){
if(str2.contains(str1.substring(firstIndex,lastIndex+1))){
if(str1.substring(firstIndex,lastIndex+1).length()>maxlength){
maxlength=str1.substring(firstIndex,lastIndex+1).length();
first=firstIndex;
last=lastIndex+1;
}

}
}
}
return str2.substring(first,last+1);
}
// return null;
}
posted @ 2021-12-03 15:36  Boerk  阅读(129)  评论(0)    收藏  举报