public static boolean work(String str, char ch)
使用递归来确定str是否至少包含一次ch。
如果是,则返回true,否则返回false
示例
work(“whynot”,“n”)返回true work(“please”,“z”)返回false
public static boolean work(String str, char ch){
//base case
if (str == null || str.equals("")){
return false;
}
//recursive case
if (ch == str.charAt(0)){
return true;
}else {
work(str.substring(1), ch);
}
return false;
}
当ch是str的第一个字符时,我的代码将正确返回“true”,但当ch位于str的任何其他部分时,返回错误的“false”答案。
请解释原因......我以为这是因为我的最后一次“回归假”;语句覆盖了递归情况下的“真实”,如果,但是当我摆脱了最后的“返回错误”;我的编译器会抱怨我错过了一个返回值。
答案 0 :(得分:2)
那是因为你没有返回递归调用的结果。
试试这个:
public static boolean work(String str, char ch){
//base case
if (str == null || str.equals("")){
return false;
}
//recursive case
if (ch == str.charAt(0)){
return true;
}else {
return work(str.substring(1), ch);
}
}