题目:
给定两个字符串str1和str2,返回两个字符串的最长公共子串。要求时间复杂度为O(M*N),额外空间复杂度为O(1)的方法。
思路:
一开始想用KMP算法解决此题,但是众所周知KMp算法需要next数组,那么空间复杂度肯定是O(n)了。后来想到了递归的方法。刚好满足题目的要求。
解题代码:
public String theLongest(String str1,String str2){
String result = new String("");
String fresult = new String("");
int max = 0;
for(int i=0;i<str1.length();i++){
result = cycle(str1, str2, i, 0,"");
if(result.length() > max){
max = result.length();
fresult = result;
}
}
return fresult;
}
public String cycle(String str1,String str2,int i,int j,String result){
if(j == str2.length()){
return result;
}
if(str1.charAt(i) == str2.charAt(j)){
result += str1.charAt(i);
i++;
j++;
}else{
j++;
}
return cycle(str1, str2, i, j,result);
}