基本上我们有两个字符串,我们被要求找到最长的公共子序列。我已经在网上搜索了解决方案,并将它们与我自己的解决方案进行了比较,我在代码中找不到任何错误。我想知道为什么它仍然无法运作。
而且,我被要求通过使用递归方法来解决这个问题
这是我的代码:
public static String longestCommonSubsequence(String a, String b){
if(a.isEmpty() || b.isEmpty()){
return "";
}
if (a.substring(a.length() - 1).equals(b.substring(b.length() - 1))){
return longestCommonSubsequence(a.substring(0, a.length() - 1), b.substring(0, b.length()
- 1)) + a.substring(a.length() - 1);
} else {
String first = longestCommonSubsequence(a, b.substring(b.length() - 1));
String second = longestCommonSubsequence(a.substring(a.length() - 1), b);
if(first.length() > second.length()){
return first;
}
return second;
}
}
以下是所有测试用例:
回复致电价值
" ABCDEFG"," BGCEHAF" " BCEF"
"她出售","贝壳" " sesells"
" 12345"," 54321 21 54321" " 123"
"高傲的老师","美味的桃子" " ecious each"
" Marty"," Helene" ""
"""乔" ""
" Suzy","" ""
" ACGGTGTCGTGCTA"," CGTTCGGCTATCGTACGT" " CGGTTCGTGT"
使用我的代码我获得了所有测试用例的StackOverFlow。
答案 0 :(得分:0)
您的LCS计算不正确。在LCS中,您需要从字符串的结尾进行比较。如果两个字符串的最后一个字符匹配则意味着它将成为您LCS的一部分。
public static String longestCommonSubsequence(String a, String b) {
int alength = a.length() - 1;
int blength = b.length() - 1;
if (alength < 0 || blength < 0)
return "";
if (a.substring(alength).equals(b.substring(blength))) {
return longestCommonSubsequence(a.substring(0, alength), b.substring(0, blength))
+ a.substring(alength);
} else {
String first = longestCommonSubsequence(a, b.substring(0, blength));
String second = longestCommonSubsequence(a.substring(0, alength), b);
if (first.length() > second.length()) {
return first;
} else {
return second;
}
}
}
答案 1 :(得分:0)
您应该将 a.substring()
更改为 a.charAt()
public static String LCS_r(String a, String b) {
int m = a.length() - 1;
int n = b.length() - 1;
if (m < 0 || n < 0)
return "";
if (a.charAt(m)==b.charAt(n)) {
return LCS_r(a.substring(0, m), b.substring(0, n)) + a.substring(m);
}
else {
String s1 = LCS_r(a, b.substring(0, n));
String s2 = LCS_r(a.substring(0, m), b);
if (s1.length() > s2.length()) {
return s1;
} else {
return s2;
}
}