找到最大公共子序列
我有以下代码,由于我试图找出的某种原因,该代码无法正常工作:
public static int score(String gene1, String gene2){
char[] a=new char[gene1.length()];
char[] b=new char[gene2.length()];
a=gene1.toCharArray();
b=gene2.toCharArray();
return score(a, b, 0,0);
}
private static int score(char[] a, char[] b, int i, int j){
if(a[i]=='\0' || b[j]=='\0')
return 0;
else if (a[i]==b[j])
return 1+score(a, b, i+1, j+1);
else
return max(score(a, b,i+1, j),score(a, b, i, j+1));
}
private static int max (int a, int b){
if (a<b) return b;
else return a;
}
这是失败的地方:
assertEquals(2, GeneAnalysis.score("ACGT","AC"));
我收到 IndexOutofBoundsError
有什么想法吗?另外,在提供帮助时,请不要更改方法参数。他们应该是这样的。
I have the following code, which does not work correctly for some reason that I am trying to figure out:
public static int score(String gene1, String gene2){
char[] a=new char[gene1.length()];
char[] b=new char[gene2.length()];
a=gene1.toCharArray();
b=gene2.toCharArray();
return score(a, b, 0,0);
}
private static int score(char[] a, char[] b, int i, int j){
if(a[i]=='\0' || b[j]=='\0')
return 0;
else if (a[i]==b[j])
return 1+score(a, b, i+1, j+1);
else
return max(score(a, b,i+1, j),score(a, b, i, j+1));
}
private static int max (int a, int b){
if (a<b) return b;
else return a;
}
Here is where it fails:
assertEquals(2, GeneAnalysis.score("ACGT","AC"));
I get an IndexOutofBoundsError
Any ideas? Also, when offering help, please do not change method parameters. They are supposed to be the way they are.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
部分原因似乎是 C 和 Java 之间的混淆......
C 对于字符串有一个空终止符,而 Java 没有。相反,要检查 Java 数组的末尾,您将需要使用 .length 属性...类似于:
根据注释进行编辑。
真的,你应该就此提出一个单独的问题......但这里是它是如何工作的。首先,您使用递归,是的,这是一个棘手的概念。维基百科可能可以帮助您了解递归的基础知识。
下面的代码更接近我的编写方式,其中的注释显示了事情发生的顺序:
Part of this seems to be a confusion between C and Java....
C has a null terminator for strings, Java does not. Instead to check for the end of a Java array you will need to use the .length attribute... something like:
Edit based on comment.
Really, you should ask a separate question on this... but here is a stab at how it works. First off you are using recursion, which, yes, is a tricky concept. Wikipedia probably can help you with the basics of recursion.
Here is the code closer to how I would write it, with comments showing you the order that things occur in:
唔。您在第一行中分配的数组会发生什么情况?
Hmm. What happens to the array that you allocated in that first line?