package com.qf.a_homework;
public class Demo02 {
public static void main(String[] args) {
//findBigSameString方法 告知他有返回值 有两个参数(字符串)
System.out.println(findBigSameString("sdfakhellossddlabcjfaaa",
"abcdskaskldhelloass"));
}
//获取两个字符串中最大相同的子串
//例如:str1 = "sdfakhellossddlabcjfaaa", str2 = "abcdskaskldhelloass"
public static String findBigSameString(String str1, String str2){
//确保str1的长度大于str2的长度
//str1.length() 查看字符串的长度 23
if(str1.length() < str2.length()){
String temp = str1;//temp中间变量 有可能要交换le
str1 = str2;
str2 = temp;
}
//最终 确保 str1的长度始终 大于 str2De长度
String result = null;
/* //从最小长度开始比较,比较的次数更多
int count = 0;
for (int i = 0; i < str2.length(); i++) {
for (int j = 0; j < str2.length() - i; j++) {
count++;
String tempStr = str2.substring(j, j + 1 + i);
if (str1.contains(tempStr)
&& (result == null || tempStr.length() > result.length())){
result = tempStr;
}
}
}*/
//从最大长度开始比较,比较的次数更少
//str1 = "sdfakhellossddlabcjfaaa"
int count = 0;
/**
* i = 18 18>=0 进入倒内层for循环
* count=0
* j=0 0<1 true
* str2.substring(j, j + i + 1); str2 = "abcdskaskldhelloass"
* str2.subString(0, 19); tempStr = "abcdskaskldhelloass"
* if (不执行的) {
*
* } j++
* j=1 1<1 false 内层for循环结束 i--
* i=17 17>=0 进入倒内层循环
* j=0 0<2
* count=1
* String tempStr = str2.substring(0, 18);
* tempStr = abcdskaskldhelloas
* if(不执行) {
* }
* j=1 1<2 true
* count=2
* String tempStr = str2.substring(j, j+i +1);
* tempStr = str2.substring(1, 19);
* tempStr = bcdskaskldhelloass
* j=2 2<2 结束
*
* i=16 16>=0
* j=0 0<3 count=3
* String tempStr = str2.substring(0, 17);
* tempStr = abcdskaskldhelloa
* if(不执行)
* j=1 1<3 count=4
* tempStr = str2.substring(1, 18);
* tempStr = bcdskaskldhelloas
* if(不执行)
* j=2 2<3 count=5
* tempStr = str2.substring(2, 19);
* tempStr = "cdskaskldhelloass"
* j=3 3<3 false
* i=15 15 >=0
* j=0 0<4 count=6
* tempStr = str2.substring(0, 16);
* tempStr = "abcdskaskldhello"
* j=1 1<4 count=7
* tempStr = str2.substring(1, 17);
* tempStr = "bcdskaskldhelloa"
* j=2 2<4 count=8
* tempStr = str2.substring(2, 18);
* tempStr = "cdskaskldhelloas"
* j=3 3<4 count=9
* tempStr = str2.substring(3, 19);
* tempStr = "abcdskaskldhelloass"
*
* ...
* i=5 5>=0
* j=0 0<14
* tempStr = str2.substring(0, 6);
* tempStr = "abcdsk"
* j=1 1<14
* tempStr = str2.substring(1, 7);
* i=4 4>=0
* j=0 0<15
* tempStr = str2.substring(0, 5);
* tempStr = "abcds"
* j=1 1<15
* tempStr = str2.substring(1, 6); tempStr = "abcdskaskldhelloass"
* tempStr = "bcdsk
* ...
* j=11 11<15
*
* tempStr = str2.substring(11, 16);//hello
*
*
* str1 = "sdfakhellossddlabcjfaaa".
* if (true && true )
*
* result = "hello"
* retrurn result
*
*/
for (int i = str2.length() - 1; i >= 0; i--) {
for (int j = 0; j < str2.length() - i; j++) {
count++;
//截取短的那个字符串进行长度依次递减的子串与较长的字符串进行比较
String tempStr = str2.substring(j, j + i + 1);
if (str1.contains(tempStr)
&& (result == null || tempStr.length() > result.length())){
result = tempStr;
System.out.println("循环次数:" + count);
//因为一旦找到就可以退出该方法了
return result;
}
}
}
return result;
}
}