我自己编写了这段代码,但我对递归很陌生,我需要一些帮助来更改此代码,以便它是递归的。我从一个基本案例开始。我试图编写代码来检查两个字符串并查看其是否相同。
public static boolean check(String s1, String s2) {
int count = 0;
if (s1.length() != s2.length()) {
return false;
else {
for (int i=0; i< s1.length(); i++){
if(s1.charAt(i) != s2.charAt(i))
return false;
count = i;
}
if(count == s1.length()-1)
return true;
}
return false;
}
最佳答案
count
变量是不必要的。您可以用递归调用替换 for
循环:
public static boolean check(String s1, String s2) {
if (s1.length() != s2.length())
return false;
return check(s1, s2, 0);
}
private static boolean check(String s1, String s2, int i) {
// this is up to you
return check(s1, s2, i+1);
}
编辑:刚刚看到作业标签
关于java - 你会如何递归地编写这段代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9696270/