递归搜索数组中的字符(Java)

AlM*_*AlM 4 java recursion

我被要求写一些能确定数组是否是另一个更大数组的子集的东西.我决定从一个更简单的问题开始,编写一个函数来确定一个字符数组中是否存在一个字符.我想出了这段代码:

private static boolean findSequenceRecHelper(char [] findIn, char c, int index) {
    boolean result = false;
    if(index<findIn.length) {
        if(findIn[index] == c) {
            result = true;
        }
        else {
            findSequenceRecHelper(findIn,c,index+1);
        }
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

我做了一些调试,发现函数遍历整个char[]数组,当数组中的元素等于所需的值时,result转向true.但后来又转向falsefalse实际返回,这是不正确的.

我在这里找不到错误 - 有人可以帮我解决这个问题.

ami*_*mit 5

在递归步骤中:

else
findSequenceRecHelper(findIn,c,index+1);
Run Code Online (Sandbox Code Playgroud)

您应该return是递归调用返回的值.否则 - 什么也没做,递归调用实际上是多余的.

private static boolean findSequenceRecHelper(char [] findIn, char c, int index)
{
boolean result = false;
if(index<findIn.length)
{
    if(findIn[index] == c)
        result = true;
    else
    return findSequenceRecHelper(findIn,c,index+1);
    //^ 
    //added return here
}
return result;
}
Run Code Online (Sandbox Code Playgroud)