最长公共子串
描述
给定两个字符串str1和str2,输出两个字符串的最长公共子串
题目保证str1和str2的最长公共子串存在且唯一。
数据范围: 1 \le |str1|,|str2| \le 50001≤∣str1∣,∣str2∣≤5000
要求: 空间复杂度 O(n^2)O(n2),时间复杂度 O(n^2)O(n2)
要求: 空间复杂度 O(n^2)O(n2),时间复杂度 O(n^2)O(n2)
示例1
输入:
"1AB2345CD","12345EF"
返回值:
"2345"
import java.util.*;
public class Solution {
/**
* longest common substring
* @param str1 string字符串 the string
* @param str2 string字符串 the string
* @return string字符串
*/
public String LCS (String str1, String str2) {
// write code here
int len1 = str1.length();
int len2 = str2.length();
String commonStr = "";
int commonLen = 0;
for(int i=0; i<len1; i++){
char temp = str1.charAt(i);
if(commonLen>(len1-i)){
return commonStr;
}
for(int j=0; j<len2;j++){
int tmpCommonLen = 0;
String tmpCommonStr = "";
int k1 = i;
int k2 = j;
while(k1<len1&&k2<len2&&str1.charAt(k1)==str2.charAt(k2)){
tmpCommonLen ++;
tmpCommonStr += str1.charAt(k1);
k1++;
k2++;
}
if(commonLen<tmpCommonLen){
commonLen = tmpCommonLen;
commonStr = tmpCommonStr;
}
}
}
return commonStr;
}
}

浙公网安备 33010602011771号