比如:
str1 = “abcwerthelloyuiodef”;
str2 = “cvhellobnm”
提示:将短的那个串进行长度依次递减的子串与较长的串比较。
只存在一个最大长度的相同子串
public String getMaxSameSubString(String str1, String str2){
if (str1 != null && str2 != null){
String maxStr = (str1.length() > str2.length()) ? str1 : str2;
String minStr = (str1.length() > str2.length()) ? str2 : str1;
int len = minStr.length();
for (int i = 0; i < len; i++){
for (int x = 0, y = len - i; y <= len; x++, y++){
if (maxStr.contains(minStr.substring(x, y))){
return minStr.substring(x, y);
}
}
}
}
return null;
}
存在多个长度相同的最大相同子串
public String[] getMaxSameSubString1(String str1, String str2){
if (str1 != null && str2 != null){
StringBuffer sBuffer = new StringBuffer();
String maxString = (str1.length() > str2.length()) ? str1 : str2;
String minString = (str1.length() > str2.length()) ? str2 : str1;
int len = minString.length();
for (int i = 0; i < len; i++){
for (int x = 0, y = len - i; y < len; x ++, y ++){
String substring = minString.substring(x, y);
if (maxString.contains(substring)){
sBuffer.append(substring + ",");
}
}
System.out.println(sBuffer);
if (sBuffer.length() != 0){
break;
}
}
String[] split = sBuffer.toString().replaceAll(",$", "").split("\\,");
return split;
}
return null;
}