以长字符串为基准串,短字符串为查找串
public String LCS(String str1, String str2) {
String standardStr;
String findStr;
//选取基准串和查找串
if (str1.length() >= str2.length()) {
standardStr = str1;
findStr = str2;
} else {
standardStr = str2;
findStr = str1;
}
//如果基准串包含查找串,直接返回查找串
if (standardStr.contains(findStr)) {
return findStr;
}
//记录相同的字符串
String temp = "";
for (int i = 0; i < findStr.length(); i++) {
//如果temp的长度大于等于剩余字符串的长度,直接跳出循环
if (temp.length() >= findStr.length() - i) {
return temp;
}
for (int j = i + 1; j < findStr.length() + 1; j++) {
if (standardStr.contains(findStr.substring(i, j))) {
if (findStr.substring(i, j).length() > temp.length())
temp = findStr.substring(i, j);
}else {
break;
}
}
}
return temp;
}